I have a question to improve my prehension 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!
I have a question to improve my prehension 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!
Share Improve this question edited Sep 8, 2022 at 16:07 Max Hay 2593 silver badges14 bronze badges asked Mar 6, 2020 at 17:55 mafehxmafehx 5112 gold badges8 silver badges16 bronze badges 2- 2 "Its said that if one passes the set state functions or hooks to the children its bad practice." Where have you read this? – Emile Bergeron Commented Mar 6, 2020 at 19:11
- 1 @EmileBergeron It would seem that the misinformation was delivered here – J D Commented Sep 1, 2020 at 15:51
1 Answer
Reset to default 16It 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
ponent 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
ponent 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.