This week Lambda students are learning React! One area where students have been confused is what is useState?
So I created a simple food app to help my husband and I decide what we should have for dinner. And to help you all understand useState 🎉
I'll be referencing this CodeSandBox throughout the article.
useState is a Hook that lets you add React state to function components.
Here we declare a new state variable, which I called "activeFood"
const [activeFood, setActiveFood] = useState(0);
It means that we’re making two new variables activeFood and setActiveFood, where activeFood is set to the first value returned by useState, and setActiveFood is the second.
It is equivalent to this code:
var foodStateVariable = useState(0); // Returns a pair var activeFood = foodStateVariable; // First item in a pair var stActiveFood= foodStateVariable; // Second item in a pair
In this instance it is declaring a "state variable" which we named activeFood. Like any variable we could name it whatever we wanted.
In React state variables are preserved. They do not vanish like they normally would when a function exits.
Per the React Docs:
The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object.
Here we pass 0 as initial state for our variable.
It returns a pair of values: the current state (our variable activeFood) and a function that updates it (setActFood). This is why we write const [activeFood, setActiveFood] = useState(0); In this app I use another function randomFood to randomize setActiveFood when the user clicks the button.
Let's review what I've done.
Line 1: We import the useState Hook from React. It lets us keep local state in a function component.
Line 36: Inside the Card component, we declare a new state variable by calling the useState Hook.
It returns a pair of values, to which we give names.
We’re calling our variable activeFood because it is the food that will be displayed.
We initialize it to zero by passing 0 as the only useState argument.
The second returned item is itself a function. It lets us update the activeFood so we’ll name it setActiveFood.
Line 48: When the user clicks, we call our function randomFood which randomizes our setActiveFood function. React will then re-render the Card component, passing the new activeFood value to it.