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!
We can set Parent State from Children Component in ReactJs using the following approach. We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting. We will create a function in parent to set the state with the given input.
Passing useState as props in another component is totally possible. But there's no benefit in doing so because you can always call useState by importing React at the top of your JavaScript code and call it in all of your components. This is a bad practice, and you should never use useState like this.
Hooks should not be called within loops, conditions, or nested functions since conditionally executed Hooks can cause unexpected bugs. Avoiding such situations ensures that Hooks are called in the correct order each time the component renders.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With