React useState - Quick guide
Jose C
Posted on November 8, 2021
What is useState?
useState it's a react built in hook that allows you to create and handle component's state.
How it works
To use this hook we just pass the initial state value and the hook will return us an array with two elements:
- The current state.
- A function to update the component's state.
React components state can be anything we may need to be: a string, array, objects you name it. We can also declare as many states as we may need on each component.
To set the initial state we can set it directly or use a function result.
With examples everything is always more clear
Imagine we have a component that renders a button and a counter showing how many times the button has been clicked.
This component may be something like this:
const App = () => {
let counter = 0;
const clickHandler = () => {
counter++;
console.log(counter);
};
return (
<div className="container">
<h1>Total clicks: {counter}</h1>
<button onClick={clickHandler}>Click!</button>
</div>
);
};
This component it's rendering a button and a counter and each time we click on the button prints on the console the counter value, however the Total clicks title it's stuck on the initial value that it's 0. Why? This is because variables only changes on the memory and has no sync with the view but we can solve this issue using the useState hook to update the counter:
First we need to import the useState:
import { useState } from "react";
const App = () => {
// Initialize the components state on 0
// useState hook returns the initial value (counter) and the function to update it (setCounter)
const [counter, setCounter] = useState(0);
const clickHandler = () => {
console.log(counter);
// state can never be modified, just overwritten
setCounter((prevState) => prevState + 1);
};
return (
<div className="container">
{/* Now when clicking on the button the state gets updated and so does the counter */}
<h1>Total clicks: {counter}</h1>
<button onClick={clickHandler}>Click!</button>
</div>
);
};
When we are using useState
the view shows the current value each time the state gets updated.
In react states can never be modified, must be overwritten.
In situations like the counter example where you need the previous state to set the new one you have to pass a function that receives the previous value and returns the new one. On the counter example the new state will be always the previous state + 1.
So variables on react are pointless? NOT AT ALL. I recommend you to use variable for anything that not needs to be rendered on the view as each time the states changes react re-renders the components to keep the view and the state up to date.
Posted on November 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 18, 2024