Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
React is a library for creating frontend views. It has a big ecosystem of libraries that work with it. Also, we can use it to enhance existing apps.
In this article, we’ll look at how to use the state hook to keep dynamic states in a function component.
Using the State Hook
We can use the React.useState
method to create a state with a corresponding function to change the state.
For example, we can write the following code to add a hook to our app:
import React from "react";
import ReactDOM from "react-dom";
function App() {
const[count, setCount] = React.useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Count {count}</button>
</div>
);
}
In the code above, we have the React.useState
hook with the default 0 passed in. It returns an array with the state, which we called count
, and a function to set the state, which is called setCount
.
Then in the onClick
handler of the button, we can the setCount
function to update the count.
Equivalent Class Example
The example above would be the same as the following class:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Count: {this.state.count}
</button>
</div>
);
}
}
In the code above, we have this.state
initialized in the constructor with count
0. Then in the button
we pass in a click event handler that calls setState
to update the count
state by incrementing it by 1.
Therefore, this.setState({ count: this.state.count + 1 })
is the same as setCount(count + 1)
and count
is the same as this.state.count
.
Hooks and Function Components
A function component looks like:
const App = props => <p>foo</p>;
or:
function App(props) {
return <p>foo</p>;
}
They were previously known as stateless components. However, now that React has hooks, they can keep their own state. Therefore, they should be called function components.
What’s a Hook?
A hook is a special function that lets us hook into React features. useState
in the example above is a hook that lets us add React state to function components.
Declaring a State Variable
useState
declares a state variable. In the example above, we have a variable called count
but we can call it anything else.
useState
has the same capabilities as this.state
that we had in a class.
Variables disappear when the function exists but state variables are preserved by React.
The only argument for useState
is the initial state. The state doesn’t have to be an object unlike classes.
We can have any type of data as the initial state.
If we want to store multiple values in state, then we’ll call useState
for each kind of data.
useState
always gives us the current state. It’s not only for creating the initial state.
Reading State
In the example, that we had:
import React from "react";
import ReactDOM from "react-dom";
function App() {
const [count, setCount] = React.useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Count {count}</button>
</div>
);
}
We get the current state from count
returned by useState
.
Updating State
Instead of calling this.setState
like we do in class components, we call the setCount
function directly.
Therefore, we don’t have to worry about the value of this
.
What Do Square Brackets Mean?
The square brackets in:
const [count, setCount] = React.useState(0);
is the destructuring assignment operation, which means that values from an array are assigned to variables depending on the position.
The first element is assigned to the first variable, the second is assigned to the second variable, etc.
const [count, setCount] = React.useState(0);
is the same as:
const countState = React.useState(0);
const count = countState[0];
const setCount = countState[1];
Using Multiple State Variables
We will call useState
as many times as we need to use multiple state variables.
For example, we can write:
function App() {
const [count, setCount = React.useState(0);
const [foo] = React.useState({ text: "bar" });
return (
<div>
<button onClick={() => setCount(count + 1)}>Count {count}</button>
<p>{foo.text}</p>
</div>
);
In the code above, we have 2 calls to useState
to create 2 states, count
and foo
.
States can have object values, so we don’t have to create too many states.
Conclusion
We can use the useState
hook to get and set dynamic states in a function component.
It returns the current state and a function to update the state in an array.
Then we can use them directly to display data and call the returned function to update the state.