Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to React
Understanding useState and useEffect in React

Understanding useState and useEffect in React

React2,539 viewsBy Admin
reactunderstandingusestateuseeffect

The Two Hooks You Use Most

useState and useEffect are the foundation of nearly every React component. Master these two and you can build most apps.

useState — Remembering Values

const [count, setCount] = useState(0);
//     ↑value  ↑setter        ↑initial

setCount(count + 1);        // direct
setCount(prev => prev + 1); // functional (safer for updates)

When you call the setter, React re-renders the component with the new value.

useEffect — Running Code After Render

// Runs after EVERY render
useEffect(() => { console.log("rendered"); });

// Runs ONCE on mount (empty deps)
useEffect(() => { fetchData(); }, []);

// Runs when "userId" changes
useEffect(() => { fetchUser(userId); }, [userId]);

The Dependency Array Explained

DepsWhen effect runs
no arrayafter every render
[]once, on mount
[a, b]when a or b changes

Cleanup Functions

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id); // cleanup on unmount
}, []);

A Complete Example

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    let active = true;
    fetch(`/api/users/${userId}`)
      .then(r => r.json())
      .then(data => { if (active) setUser(data); });
    return () => { active = false; };
  }, [userId]);

  if (!user) return <p>Loading...</p>;
  return <h1>{user.name}</h1>;
}

FAQs

Why shouldn't I update state inside useEffect without deps?

It causes an infinite loop — the update triggers a render, which re-runs the effect. Always specify dependencies.

Can I have multiple useState/useEffect?

Yes — use as many as you need. It keeps related logic grouped. More in our React guides.