The React useState Hook
Hooks are magic. At least that’s what I am told, and after having used them a few times, hooks are magic. The hook that I’ve used most frequently is the useState hook.
What the heck is a hook? It’s a state management and side-effect tool introduced by the React team to make functional components a bit more dynamic. With hooks, you can make functional components more powerful thus eliminating a lot of refactoring and extra files one would need to keep functional components well, functional.
The useState hook allows a functional component to “hook” into that components state. Instead of creating an entire class component that would then need to use the setState function, and also keeping in mind that the state should come from a single source, we can bypass all that extra work if we need something simple done like a counter.
The counter frequently comes up as a good example of how to use a setState. Let’s see this in a regular class component:
Now let’s check out the same counter using the useState hook:
As you can see there isn’t much code to get the same functionality, and the counters state and method for when the button is clicked doesn’t have to be placed elsewhere. Simple. Easy. Fun.
I hope you get to use the useState hook in your projects and see just how magical it can be!
Resources: