JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
Next

Learn the concept

Hooks

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

Modern Alternatives to useEffect for Data Fetching:

  • React 19's use() hook reads promises with Suspense integration
  • Framework-level data fetching (Server Components, route loaders) is now preferred
  • Libraries like TanStack Query abstract away the useEffect boilerplate
  • useEffect remains appropriate for subscriptions, DOM manipulation, and non-data side effects

Code Examples

useState patternsJSX
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>;
}

Real-World Applications

Use Cases

Theme Switching

Using useState for theme state and useEffect to apply CSS variables or class changes to the document

Window Resize Handling

useEffect with resize event listeners for responsive component behavior

Local Storage Sync

Persisting user preferences with useState + useEffect to sync with localStorage

Mini Projects

Custom Hook Collection

beginner

Build 5 reusable hooks (useLocalStorage, useDebounce, useMediaQuery, useOnClickOutside, useToggle)

Real-Time Clock

intermediate

Build a clock component exploring useEffect cleanup, intervals, and timezone handling

Industry Examples

Vercel

Uses hooks extensively for real-time deployment status updates in their dashboard

TanStack Query

Built on top of useState and useEffect patterns for data fetching abstraction

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?
Next