useState
?useState
is a Hook that lets you add React state to function components. Before hooks, state management was primarily the domain of class components. useState
changes this by allowing functional components to have state, without needing to convert them into classes.
The useState
hook returns a pair: the current state value and a function that lets you update it. Here’s how you declare state in a component:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [ count, setCount ] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
const [state, setState] = useState(initialState);
state
- The current state.setState
- The function to update the state.initialState
- The value (or a function returning the value) you want the state to be initially.useState
Immutability: When updating state, treat the previous state as immutable. For complex state changes, especially with objects or arrays, use the functional update form:
setCount(prevCount => prevCount + 1);
Multiple State Variables: You can use useState
multiple times in one component:
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
Lazy Initial State: If the initial state is the result of an expensive computation, you can pass a function to useState
, which will be executed only on the initial render:
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
State Updates are Merged: Unlike setState
in class components, useState
does not automatically merge update objects. You need to handle this manually if you’re updating an object:
const [user, setUser] = useState({ name: 'Alice', age: 20 });
setUser(prevUser => ({ ...prevUser, age: prevUser.age + 1 }));
Keep Components Small: Smaller components are easier to manage with useState
. If your state logic becomes too complex, consider using useReducer
for better state management or breaking down the component.
Use Meaningful State Names: Choose variable names that reflect what the state represents for better readability.
Avoid Unnecessary State: Only use state for values that need to trigger re-renders when changed. For values that can be computed from props or existing state, consider using useMemo
or simple calculations within the render.
Functional Updates: Always use the functional form of setState
when the new state depends on the previous state to avoid issues with stale state in asynchronous updates.
useState
has simplified state management in React, making functional components more powerful and preferable for many developers. By understanding and applying useState
effectively, you can write cleaner, more maintainable React code. Remember, with great power comes great responsibility; use state judiciously to keep your components efficient and easy to understand.