Reputation: 511
I have a question to improve my comprehension of react hooks. Its said that if one passes the set state functions or hooks to the children its bad practice. So one should just pass a handler function to the child which is located in the parent and then uses the set state functions in there. As I came across this after developing many working parts of an application I would like to know why this has to be avoided as it worked fine for me.
I hope you guys understand my issue without code examples, if I need to clarify I would ofc provide some snippets.
Thanks in advance!
Upvotes: 10
Views: 4389
Reputation: 670
It isn't bad practice to pass a state setter function to a child, this is totally acceptable. In fact, I would argue that doing this:
const MyComponent = () => {
const [state, setState] = useState();
return <Child onStateChange={setState} />
}
const Child = React.memo(() => {...});
is better than
const MyComponent = () => {
const [state, setState] = useState();
return <Child onStateChange={(value) => setState(value)} />
}
const Child = React.memo(() => {...});
because in the first example the Child
component is not rerendered whenever MyComponent
renders. In the second example whenever MyComponent
renders, it is re-creating the custom state setter function, which forces the Child
component to unnecessarily render. To avoid this, you would need to wrap your custom setter function in React.useCallback
to prevent unnecessary rerenders, which is just another arbitrary layer of hooks.
Upvotes: 16