JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
Next
react
mid
hooks

Explain the useState and useEffect hooks and their common patterns.

hooks
useState
useEffect
state
side-effects
Quick Answer

useState manages local state in functional components, returning a value and setter function. useEffect handles side effects (data fetching, subscriptions, DOM manipulation) and runs after render. The dependency array controls when effects re-run.

Detailed Explanation

useState:

  • Declares state variable in functional component
  • Returns [currentValue, setterFunction]
  • Setter can take new value or updater function
  • State persists across re-renders
  • Each useState call is independent

useEffect:

  • Runs side effects after render
  • Replaces componentDidMount, componentDidUpdate, componentWillUnmount
  • Dependency array controls execution:
    • No array: runs after every render
    • Empty array []: runs once on mount
    • [deps]: runs when deps change
  • Cleanup function runs before next effect and on unmount

Code Examples

useState patterns
function Counter() {
  // Basic usage
  const [count, setCount] = useState(0);
  
  // Lazy initialization (expensive computation)
  const [data, setData] = useState(() => {
    return computeExpensiveInitialValue();
  });
  
  // Object state
  const [form, setForm] = useState({ name: '', email: '' });
  const updateField = (field, value) => {
    setForm(prev => ({ ...prev, [field]: value }));
  };
  
  // Functional updates (when new state depends on previous)
  const increment = () => {
    setCount(prev => prev + 1); // Always uses latest value
  };
  
  // Multiple rapid updates
  const incrementThree = () => {
    // Wrong: all use same stale value
    // setCount(count + 1); setCount(count + 1); setCount(count + 1);
    
    // Correct: each uses updated value
    setCount(c => c + 1);
    setCount(c => c + 1);
    setCount(c => c + 1);
  };
  
  return <button onClick={increment}>{count}</button>;
}

Resources

React Docs - useState

docs

React Docs - useEffect

docs

A Complete Guide to useEffect

article

Related Questions

What are custom hooks and how do you create them?

mid
hooks

What is useRef and when should you use it?

mid
hooks
Next
What is React Context and when should you use it?