Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Understanding useState Hook in React

Master the useState hook to manage component state in React functional components.

jiocoder TeamUpdated Jun 6, 20261 min readReact
Understanding useState Hook in React

Introduction to useState#

The useState hook is one of the most fundamental hooks in React. It allows functional components to have state, which was previously only possible with class components.

Basic Syntax#

Code
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

How useState Works#

useState returns an array with two elements:

  • Current state value - The current value of the state
  • State setter function - Function to update the state

Initializing State#

Code
// With a primitive value
const [name, setName] = useState("John");

// With a number
const [age, setAge] = useState(25);

// With an object
const [user, setUser] = useState({
  name: "John",
  email: "john@example.com"
});

// With a function (lazy initialization)
const [data, setData] = useState(() => {
  return expensiveComputation();
});

Updating State#

Code
// Direct update
setCount(count + 1);

// Functional update (recommended when using previous state)
setCount(prevCount => prevCount + 1);

// Updating objects
setUser({ ...user, name: "Jane" });

// Updating arrays
setItems([...items, newItem]);

Common Patterns#

Code
// Multiple state variables
function Form() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [age, setAge] = useState(0);
  
  // Or combine into one object
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    age: 0
  });
}

Best Practices#

  • Use functional updates when the new state depends on the previous state
  • Don't mutate state directly - always create new objects/arrays
  • Split complex state into multiple useState calls if they're independent
  • Use lazy initialization for expensive computations

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment