DEV Community

Cover image for React Hooks Explained: useState and useEffect Simplified
Vijay Kumar
Vijay Kumar

Posted on

React Hooks Explained: useState and useEffect Simplified

React Hooks have revolutionized how we write components. If you're coming from a class-based background or just starting with React, understanding useState and useEffect is essential—they are the building blocks of functional components.

Let’s break them down.


🔹 useState: Adding State to Functional Components

Before Hooks, state was only available in class components. With useState, you can now add state to functional components easily.

Syntax:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0); // Initial value is 0

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

How it works:

  • useState returns a pair: the current state value (count) and a function to update it (setCount).
  • When you call setCount, the component re-renders with the new value.

Use it when:

  • You need to store and update values like form inputs, counters, toggles, etc.

🔹 useEffect: Side Effects in Functional Components

Side effects include things like:

  • Fetching data
  • Setting up subscriptions
  • Manually changing the DOM

In class components, you’d use lifecycle methods. In functional components, we use useEffect.

Syntax:

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

const Timer = () => {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    // Cleanup function to avoid memory leaks
    return () => clearInterval(interval);
  }, []); // Empty dependency array = run once after first render

  return <div>Time: {seconds}s</div>;
};
Enter fullscreen mode Exit fullscreen mode

How it works:

  • useEffect runs after the component renders.
  • The optional dependency array controls when it runs:

    • [] → run once (like componentDidMount)
    • [count] → run when count changes
    • No array → run after every render

Use it when:

  • You need to perform side effects like API calls, event listeners, or timers.

🧠 Bonus Tips

  • Multiple useEffect hooks are allowed. Organize logic by concern.
  • Avoid putting async directly in useEffect. Instead, define an async function inside it and call it.
  • Remember to clean up effects like subscriptions or intervals.

🔚 Wrapping Up

Understanding useState and useEffect gives you the power to build dynamic and responsive components using only functions. These two hooks are foundational—master them, and you'll be well on your way to React fluency.


Next Up: Learn about useRef, useContext, and custom hooks to deepen your React skills.

Top comments (0)