How to transfer state between React components with hooks?

Viewed 2862

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?

3 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

Perhaps, you should ask yourself why you would like to use inheritance. It seems like for many cases where many developers tend to immediately think about using OOP-style inheritance, React.js might recommend composition instead (see https://reactjs.org/docs/composition-vs-inheritance.html).

With functional components, composition is probably the only choice, which means that your "parent" component would render the "child" component, passing whatever state it needs to pass via the child's props.

Whether your project needs Redux or not should be completely orthogonal to the composition-vs-inheritance question.

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!

Related