Using the State Hook Flashcards
What does calling useState do?
It declares a “state variable”.
import React, { useState } from ‘react’;
function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
Our variable is called count but we could call it anything else, like banana. This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.
What do we pass to useState as an argument?
The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need.
What would you do if you wanted to store two different values in a state?
If we wanted to store two different values in state, we would call useState() twice.
What does useState return?
It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(). This is similar to this.state.count and this.setState in a class, except you get them in a pair.
Example of useState being used
import React, { useState } from ‘react’;
function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
We declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.
Why is useState not named createState instead?
“Create” wouldn’t be quite accurate because the state is only created the first time our component renders. During the next renders, useState gives us the current state. Otherwise it wouldn’t be “state” at all.
How do you read state in a function component?
When we want to display the current count in a class, we read this.state.count:
<p>You clicked {this.state.count} times</p>
In a function, we can use count directly:
<p>You clicked {count} times</p>
How do you update state?
In a class, we need to call this.setState() to update the count state:
this.setState({ count: this.state.count + 1 })}>
Click me
In a function, we already have setCount and count as variables so we don’t need “this”:
setCount(count + 1)}>
Click me
What Do Square Brackets Mean?
const [fruit, setFruit] = useState(‘banana’);
This JavaScript syntax is called “array destructuring”. It means that we’re making two new variables fruit and setFruit, where fruit is set to the first value returned by useState, and setFruit is the second. It is equivalent to this code:
var fruitStateVariable = useState('banana'); // Returns a pair var fruit = fruitStateVariable[0]; // First item in a pair var setFruit = fruitStateVariable[1]; // Second item in a pair
When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it.
Describe useState
useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.
The only argument to useState is the initial state. Note that unlike this.state, the state here doesn’t have to be an object — although it can be if you want. The initial state argument is only used during the first render.
Stateful logic
The state of each component is completely independent. Hooks are a way to reuse stateful logic, not state itself. In fact, each call to a Hook has a completely isolated state — so you can even use the same custom Hook twice in one component.
Using Multiple State Variables
Declaring state variables as a pair of [something, setSomething] is also handy because it lets us give different names to different state variables if we want to use more than one:
function ExampleWithManyStates() { // Declare multiple state variables! const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
In the above component, we have age, fruit, and todos as local variables, and we can update them individually:
function handleOrangeClick() { // Similar to this.setState({ fruit: 'orange' }) setFruit('orange'); }
You don’t have to use many state variables. State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike this.setState in a class, updating a state variable always replaces it instead of merging it.
How does React know which state corresponds to which useState call?
The answer is that React relies on the order in which Hooks are called. As long as the order of the Hook calls is the same between renders, React can associate some local state with each of them.