useState
The useState
hook is one of the most commonly used hooks in React. It allows you to add state to functional components. Before hooks were introduced, state could only be used in class components. The useState
hook makes it possible to manage state in a more straightforward way within functional components.
Basic Syntax
The basic syntax of useState
is as follows:
const [state, setState] = useState(initialState);
initialState
: The initial value of the state variable. This can be any data type.state
: The current state. Please note we can use any other variable name heresetState
: A function to update the state. We could use any function name here.
How it Works
Initialization: When a component mounts,
useState
initializes the state variable with the provided initial value.Render: The component renders using the initial state.
Update: When you want to update the state, you call the
setState
function. This triggers a re-render of the component.Re-render: React will re-render the component with the updated state.
Example
Here's a simple example to demonstrate how useState
works:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable named "count" with an initial value of 0
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
{/* When the button is clicked, setCount will update the state */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In this example:
useState(0)
initializescount
with a value of 0.setCount
is the function used to update thecount
state.- Clicking the button calls
setCount
, which updates the state and causes the component to re-render.
Multiple useState
You can use multiple useState
hooks in a single component to manage different pieces of state:
const [name, setName] = useState('John');
const [age, setAge] = useState(30);
Each call to useState
provides a separate piece of state, allowing you to isolate concerns and make your components more modular.
Lazy Initialization
You can also lazily initialize your state by passing a function to useState
:
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation();
return initialState;
});
This is useful when the initial state is computationally expensive to produce. The function inside useState
will only be run once during the initial render.
That's a brief overview of how useState
works in React. It's a powerful feature that makes state management in functional components both possible and efficient.