Custom Hooks: A Flexible Feature
The two independent states of Demo1
and Demo2
show a very important feature of custom Hooks: you use them to share logic, not to share state. If you needed to share state across components, you would do so with React context (see the previous chapter).
When using Hooks, every component uses its own "instance" (or "version") of that Hook. It's always the same logic, but any state or side effects handled by a Hook are handled on a per-component basis.
It's also worth noting that custom Hooks can be stateful but don't have to be. They can manage state via useState()
or useReducer()
, but you could also build custom Hooks that only handle side effects (without any state management).
There's only one thing you implicitly have to do in custom Hooks: you must use some other React Hook (custom or built-in). This is because, if you didn't include any other Hook, there would be no need to build a custom...