最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Hooks : Why is it bad practice to pass the set state functions to a Child Component? - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 16

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 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论