React Interview Reference

Back to home

useState Hook

The useState hook lets you add state to functional components.

Basic Usage

useState returns a stateful value and a function to update it.

jsx
import { useState } from 'react';

function Counter() {
  // Declare a state variable named "count" with initial value 0
  const [count, setCount] = useState(0);

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

Using Objects with useState

When using objects with useState, you need to spread the previous state.

jsx
import { useState } from 'react';

function UserForm() {
  const [user, setUser] = useState({
    name: '',
    email: ''
  });

  const handleNameChange = (e) => {
    // Spread the previous state and update only the name property
    setUser({ ...user, name: e.target.value });
  };

  const handleEmailChange = (e) => {
    setUser({ ...user, email: e.target.value });
  };

  return (
    <form>
      <input
        value={user.name}
        onChange={handleNameChange}
        placeholder="Name"
      />
      <input
        value={user.email}
        onChange={handleEmailChange}
        placeholder="Email"
      />
    </form>
  );
}

Functional Updates

If the new state depends on the previous state, use the functional update form.

jsx
import { useState } from 'react';

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

  // This is safer for concurrent updates
  const increment = () => {
    setCount(prevCount => prevCount + 1);
  };

  return (
    <button onClick={increment}>
      Increment
    </button>
  );
}

Lazy Initial State

If the initial state is expensive to compute, provide a function instead.

jsx
import { useState } from 'react';

function ExpensiveInitialState() {
  // The function is only called during the first render
  const [state, setState] = useState(() => {
    const initialState = someExpensiveComputation();
    return initialState;
  });

  return (
    // Component JSX
  );
}

Common Interview Questions

  • ?
    What is the difference between class component state and useState?
  • ?
    Why might you need multiple useState calls in a single component?
  • ?
    How do you update state that depends on the previous state?
  • ?
    What happens when you call a state setter function during rendering?
  • ?
    How does React batch state updates?