Using the State Hook for State Management in React
My previous post, Props vs State in React, mentioned the necessity of using class components in order to control state in React before hooks were added. This post will show how the setState Hook can be used in functional components to manage state since their addition in the release of React 16.8.0 in Feb, 2019 .
Hooks were introduced to React to simplify components. They allow access to React state and lifecycle features without using class components. You can create your own Hooks to reuse stateful behavior, but this post will focus on one of the built-in Hooks. By convention, they begin with ‘use’.
STATE HOOK
The built-in Hook for adding local state to a component and preserving it through re-renders is useState.
In the below example, the useState Hook is used to set the initial state for name. This initial state argument will only be used on the first render of the component.
you can see that name and setName are declared together, as related variables. useState returns both the current state value, and a function that lets you update it. It can be thought of similar to this.setState, and can similarly be called from an event handler.
A major difference between useState and this.setState is that useState replaces the old state; it does not merge old and new state together. If you have another unrelated variable that you want to keep track of as state, you can declare it next to the first at the top of the function, and access it directly by variable name, rather than collecting them together and accessing through a single state object.
Calling setName or setDiscovery will trigger React to re-render this component.
RULES FOR USING HOOKS
It is important to Hooks at the top level of your functional components. This will enable React to reliably persist state through re-renders.
Hooks can be used within custom Hooks. See the React documentation for more info on this.
MORE INFO
For more detailed information on using Hooks, check out the React documentation on hooks here.
Check out my post on Props vs State in React.
I am forever improving. If you have corrections or feedback, I would be happy to learn and make fixes. Thank you!