0
0
ReactHow-ToBeginner · 3 min read

How to Use useState in React: Simple State Management

In React, you use the useState hook to add state to functional components. It returns a state variable and a function to update it, allowing your component to remember values and update the UI when those values change.
📐

Syntax

The useState hook is called inside a functional component. It takes the initial state value as an argument and returns an array with two items: the current state and a function to update that state.

  • Initial state: The starting value for your state.
  • State variable: Holds the current value.
  • Setter function: Updates the state and triggers UI refresh.
javascript
const [state, setState] = useState(initialValue);
💻

Example

This example shows a simple counter that starts at 0. Clicking the button increases the count by 1 using useState.

javascript
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;
Output
You clicked 0 times (initially). Each button click increases the number shown by 1.
⚠️

Common Pitfalls

Some common mistakes when using useState include:

  • Trying to update state directly instead of using the setter function.
  • Not initializing state properly, leading to unexpected values.
  • Using the old state value inside the setter without a function when updates depend on previous state.

Always use the setter function to update state and consider using a function inside the setter if the new state depends on the old one.

javascript
/* Wrong way: Directly modifying state (do NOT do this) */
// count = count + 1; // This won't update the UI

/* Right way: Using setter function */
setCount(count + 1);

/* Right way when new state depends on old state */
setCount(prevCount => prevCount + 1);
📊

Quick Reference

ConceptDescriptionExample
ImportBring useState from Reactimport React, { useState } from 'react';
Declare stateCreate state variable and setterconst [value, setValue] = useState(initial);
Update stateUse setter to change statesetValue(newValue);
Update based on old stateUse function form for safetysetValue(prev => prev + 1);

Key Takeaways

Use useState inside functional components to add state.
Always update state using the setter function returned by useState.
Initialize state with a proper starting value to avoid bugs.
Use the function form of the setter when new state depends on previous state.
Remember that updating state triggers React to re-render the component.