If we build React applications with functional components, the managing state can be a bit tricky. Fortunately, React provides a powerful hook useState
that can simplify your code and help you manage state more efficiently.
In this post, we’ll explore how useState
works and show you three simple steps to manage state in React functional components.
What is useState
and How Does it Work?
useState
is a hook provided by React that allows functional components to manage state. When you call useState
, you pass in an initial state value and it returns an array with two values:
- the current state value
- a function
Here’s an example:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // ... }
In this example, we’re declaring a state variable called count
and a function to update the state variable called setCount
. We’re also initializing the count
variable to 0
using useState(0)
.
Step 1: Declare a State Variable
In the above example, we’re declaring a state variable called count
and initializing it to 0
using useState(0)
.
Step 2: Update the State Variable
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleIncrement() { setCount(count + 1); } // ... }
Step 3: Use the State Variable in Your Component
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleIncrement() { setCount(count + 1); } return ( <div> <h1>Count: {count}</h1> <button onClick={handleIncrement}>Increment</button> </div> ); }
Conclusion
By following these steps, you can declare and update state variables in your component and use them to render dynamic content.