Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Alternative: useReducer + useContext #3
This is meant to demonstrate an alternative to #2 which might make sense for larger apps. It helps you avoid the need for passing callbacks altogether which alleviates most of these concerns. The reducer form is also more flexible because you can use other state variables, or even props (by putting reducer itself inline into the component).
The general recommendation btw is that you can keep using callbacks closer to leaf components that don’t contain a lot of computation. Such as a Button in a real app (not this one which is artificially expensive).
But that when you need to tie some application logic together that might go through many levels, that’s when you use some dispatch context. This neatly avoids having to change a dozen components each time you need a new “event” emitted from a child that affects grandparent state.
So there will be boundaries where your code will look like
The leaf components are fully controlled by props, but components that tie into app logic require a context above them. Note this doesn’t make them “untestable” etc. You can always put the same context above them in tests, but provide a different implementation for it.