Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer state between React components with hooks?

With React classes when you have state in the constructor you could inherit it to the child component directly and from the child to the parent using callbacks. How can you transfer state from parent to child with hooks? Is the only way useReducer or Redux?

like image 692
Fotios Tragopoulos Avatar asked Aug 16 '26 23:08

Fotios Tragopoulos


2 Answers

The concepts of passing props down to child or conveying information from child to parent hasn't changed with the arrival of hooks.

Hooks provide, you a way to use lifecycle like functionality and states with functional components.

you can declare your state in parent with useState and pass it down as props to child component as you would normally have done with class components or functional components previously

For example:

const Parent =() => {
  const [count, setCount] = useState(0);
  return <Child count={count} setCount={setCount} />
}

const Child = ({count, setCount}) => {
  const updateCount = () => {
     setCount(prev=> prev + 1);
  }
  return (
      <div>
         <div>Count: {count}</div>
         <button type="button" onClick={updateCount}>Increment</button>
      </div>
}

You can refer this post for more details on lifecycles with hooks:

ReactJS lifecycle method inside a function Component

Please refer the react docs with hooks FAQs

like image 138
Shubham Khatri Avatar answered Aug 18 '26 15:08

Shubham Khatri


Classes and functional components (or func-comp as my mate calls them) are the same in respect to props.

You can pass props from parent to child in a functional component just like how you'd do with a class.


//Parent

const Parent = () => {

const [state, setState] = React.useState({ products: 1, isAvailable: true})

const addProduct = (data) => {
// Your function
}

return (
<Child product info={state} addProduct={addProduct} />

)

}


export default Parent


And in the child component you can receive the props typically the way you would will classes.


const Child = ({productInfo, addProduct}) => {
 // Do what ever you like with the props
}


Cheers!

like image 39
Suraj Auwal Avatar answered Aug 18 '26 15:08

Suraj Auwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!