React Hooks Deep Dive: useState and useEffect
TutorialsReact Hooks Series - Part 1

React Hooks Deep Dive: useState and useEffect

Master the two most important React Hooks with practical examples and common patterns

Romeo Mukulah

Romeo Mukulah

Jan 18, 20268 min
6578

React Hooks Deep Dive: useState and useEffect

Hooks revolutionized React development. Let's master the fundamentals.

useState: Managing State

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

useEffect: Side Effects

import { useEffect, useState } from "react";

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  }, [userId]); // Re-run when userId changes
  
  if (!user) return <div>Loading...</div>;
  
  return <div>{user.name}</div>;
}

Common Patterns

Cleanup Functions:

useEffect(() => {
  const timer = setInterval(() => {
    console.log("Tick");
  }, 1000);
  
  // Cleanup
  return () => clearInterval(timer);
}, []);

Stay tuned for Part 2 covering useContext and useReducer!

Comments (8)

No comments yet. Be the first to comment!