What is useState?
The useState hook is the most popular and widely used hook in React. It lets you have state in a functional component. Before the useState hook came out, (React 16.8 🎉), you could only have state in class based components 😭.
How do you use it?
useState is a function.
useState()
That function returns 2 things: the state, and a function to update that state. You typically access those through array destructuring.
const [state, setState] = useState()
You can pass that function an initial state.
const [state, setState] = useState(initialState)
That initial state can be anything: a number, a boolean, a string... It can even be a function that returns the initial state.
💡 That function would only be called on the
initial render. Not every time the state is updated or on
every re-render. So having a more expensive function here is
ok if you need it.
We'll start off with the classic counter example. So the initial state will be 0.
const [state, setState] = useState(0)
It's good practice to name the state (and setState) something that refers to that state. Since we're using our state as a counter, we'll name our state count (and our updater function setCount).
const [count, setCount] = useState(0)
Accessing the State
We can access our state in our component simply by using the const variable we assigned to our state. In our case, count
.
<p>Our count number is: {count}</p>
This will render:
Updating the State
Now we'll create a button that when clicked, it will update the state.
<button onClick={() => setCount(count + 1)}>count it!</button>
In this example, we're inserting the code to update the state right inside setCount (count + 1). We could also call a function that has more logic, then update the state in that function.
const countHandler = () => {
// more logic could go here
//(reach out to an api, more calculations, etc..)
const updatedCount = count + 1;
setCount(updatedCount)
}
<button onClick={countHandler}>count it!</button>
This would have the same behavior.
Conclusion
useState can be used for all sorts of things: grabbing a user's input from a form, toggling a boolean for a mobile sidebar, or even having an array of blog posts you retrieved from a database and mapping over them to display each post.
I go over a lot more examples in my YouTube video about useState here, and I focus specifically on form handling here.
Hope this helped someone and thank you for reading!
-Andrew
Top comments (1)
Dope post. I had a question, how did you create and emebd the video that showcases the result of the code?