Do custom hooks share states?
The per-requisite for this blog is a basic understanding of react and enough JS to be able to create a function.
Before I start babbling about custom hooks let’s revisit what are hooks in react. A “Hook” in react is a functionality that let’s you work with states and lifecycle features of the functional components.
Functions like useState
& useEffect
are a couple of examples of hooks in react. So the hooks are functions with ability to interact with states and lifecycle features of components in react.
Now What are custom hooks?
These are the functions that you create to separate a “stateful logic” that is being used or needed in multiple places in your code. It is like a util
function that you create to reduce code duplication by creating a whole separate function.
Now you know what are custom hooks but how to create one? What are the parameters to keep in mind while creating one?
- Their name should start with “use” like
useExampleHook
. The reason react enforce us to use this prefix as it can then know that that particular function is actually a hook and prompt linting errors regarding hooks for that like hooks can be used only inside functional components. - It should use a react hook directly or indirectly. Since a hook is a function that interacts with state and lifecycle features, it needs react hooks to be able to do so.
That’s all you need to know to start creating your own hooks.
The most confused aspect of custom hooks
Once you have a custom hook say that it uses useState
to update a state after doing some operations on it and returns the state
and setState
function to let the user to use the state and set it dynamically as useState
does but with some extra work you want it to do in between.
Now the question arises that can two separate components using this custom hook share same state among themselves? in other words if one component invokes the setState
function will it reflect in the other?. The answer is NO.
Since custom hooks are simple functions and does not have abilities like React context API (If you don’t know about this don’t worry) that can share state. Also as it is a function that uses the useState
hook inside it, so, on every new or separate invocation of this hook, it creates a new state which is totally isolated from any other state created from this hook.
That was all folks, with this you get a good idea of what a custom hook is, to know more about custom hooks I’ll suggest to refer react docs (Here). Till then have good time learning new things, clap if you liked it, let me know if you didn’t and subscribe, follow for more blogs like this. 🙌
Signing off Soyokaze ❤