How to Use useState Hook in Next.js for State Management
In Next.js, you use the
useState hook inside functional components to create and manage state variables. Import useState from React, then call it to get a state value and a function to update it, which triggers UI updates automatically.Syntax
The useState hook is imported from React and used inside a functional component. It returns an array with two items: the current state value and a function to update that value.
Example parts:
const [state, setState]: Destructures the array into a state variable and its updater function.useState(initialValue): Initializes the state withinitialValue.
javascript
import { useState } from 'react'; function Component() { const [state, setState] = useState(initialValue); // state is current value // setState updates the value and re-renders }
Example
This example shows a simple counter that increases when you click a button. It demonstrates how useState holds the count and updates the UI when the button is clicked.
javascript
import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <main style={{ padding: '1rem', fontFamily: 'Arial, sans-serif' }}> <h1>Counter: {count}</h1> <button onClick={() => setCount(count + 1)} aria-label="Increase count"> Increase </button> </main> ); }
Output
A page showing "Counter: 0" and a button labeled "Increase". Clicking the button increments the number shown.
Common Pitfalls
Common mistakes when using useState in Next.js include:
- Calling
useStateoutside a component or conditionally, which breaks React rules. - Mutating the state directly instead of using the updater function, causing UI not to update.
- Forgetting to import
useStatefrom React.
Always call useState at the top level of your component and use the updater function to change state.
javascript
/* Wrong: useState called conditionally */ // if (someCondition) { // const [value, setValue] = useState(0); // ❌ Don't do this // } /* Right: useState called unconditionally */ function Component() { const [value, setValue] = useState(0); // ✅ Correct return null; }
Quick Reference
Tips for using useState in Next.js:
- Always import
useStatefromreact. - Initialize state with a value or function returning a value.
- Use the updater function to change state and trigger re-render.
- Keep state updates immutable (do not modify state directly).
- Use descriptive names for state variables and updater functions.
Key Takeaways
Import and use
useState inside functional components to manage state in Next.js.Always call
useState at the top level of your component, never inside conditions or loops.Use the updater function returned by
useState to change state and update the UI.Avoid mutating state directly; always replace it with a new value.
Descriptive state variable names improve code readability and maintenance.