.NET  

Deep Dive into React Hooks: useEffect, useReducer, and useMemo

React introduced hooks to bring state management, side effects, and performance optimizations to functional components. Among the most important ones are useEffect, useReducer, and useMemo.

Let's explore them in detail with icons, syntax, examples, and best practices.

⚡ useEffect – Side Effects

🛠 What does it do?

  • Handles side effects (things outside the component's render).

  • Examples include data fetching, subscriptions, timers, and manual DOM updates.

  
    useEffect(() => {
  // effect logic here

  return () => {
    // cleanup logic here (optional)
  };
}, [dependencies]);
  

✅ Best Use Cases

  • Fetching API data.

  • Setting up subscriptions (WebSocket, Firebase, etc.).

  • Handling intervals/timers.

  • Cleaning up on unmount.

  
    import { useReducer } from "react";

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <h1>Count: {state.count}</h1>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </>
  );
}
  

🔍 Purpose⏳ When It Runs🎯 Best Use Case
Handle side effects (API calls, timers, subscriptions, DOM updates)Data fetching, event listeners, intervals, and cleanupData fetching, event listeners, intervals, and cleanup
Manage complex state using reducer & actionsData fetching, event listeners, intervals, and cleanupData fetching, event listeners, intervals, and cleanup