Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks : Why is it bad practice to pass the set state funcitons to a Child Component?

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!

like image 451
mafehx Avatar asked Mar 06 '20 17:03

mafehx


People also ask

Can I setState in child component?

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.

Is it bad to practice setState as prop?

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.

What is the practice to avoid when using React Hooks?

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.


1 Answers

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.

like image 53
Bill Metcalf Avatar answered Nov 15 '22 16:11

Bill Metcalf