Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

While I don't disagree with you generally, this part

> The second problem is that your component will needlessly re-render in those cases where the component is not entirely functional.

is addressed by the react developers in the FAQ [1].

The answer wasn't obvious to me, so I made a toy example in CodeSandbox [2]. There are 3 counters that can be updated using 3 corresponding buttons. Each counter uses a different approach:

1. The "handler" counter uses "useState" + "inner function in the parent's body". The corresponding button rerenders every time the parent rerenders (i.e.: the problem you are highlighting)

2. The "callback" counter uses "useState" + "useCallback" to memoize over the counter's value. The button rerenders only when it is clicked (and hence the counter it controls is updated).

3. The "reducer" counter uses a react context to inject a "dispatch" function that calls an out-of-parent reducer. The button never rerenders. The docs are clearly pushing the reader towards this solution (albeit it is contrived for very simple examples such as this one, I can see the benefits surpassing the boilerplate overhead of reducers in more complex situations).

[1] https://reactjs.org/docs/hooks-faq.html#are-hooks-slow-becau...

[2] https://codesandbox.io/s/r584lz2pom



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: