React  

Master React Hooks: useState, useEffect & Custom Hooks Guide

React is a popular JavaScript library for building user interfaces. In React 16.8, a new feature called Hooks was introduced. Hooks allow developers to use state, lifecycle methods, and other React features in functional components without writing class components.

🔎 What are Hooks?

Hooks are special functions that let you “hook into” React features. They,

  • Always start with use (e.g., useState, useEffect).
  • Work only inside functional components.
  • Make code shorter, reusable, and easier to maintain.

✅ Benefits of Hooks

  • Cleaner Code: No need for classes.
  • Reusable Logic: Custom Hooks help reuse stateful logic.
  • Easy to Understand: Simpler syntax for beginners.
  • Efficient: Functional components are lighter than classes.

🛠️ Commonly Used Hooks

1️⃣ useState 🗂️

Let's you add state to functional components.

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click Me</button>
    </div>
  );
}

Here, count is the state variable, and setCount updates it.

2️⃣ useEffect ⚡

Handles side effects like API calls, subscriptions, or DOM updates.

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

function Example() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then(res => res.json())
      .then(json => setData(json));
  }, []); // Runs only once

  return <div>{data ? data.title : "Loading..."}</div>;
}

📌 useEffect runs after rendering. The [] means it runs only once.

3️⃣ useContext 🌍

👉 Let's you access global values from React Context API without props drilling.

4️⃣ useRef 🔗

👉 Stores a reference to a DOM element or a value that doesn’t cause re-renders.

5️⃣ useReducer ⚖️

👉 Useful for complex state management, like a mini Redux.

🛠️ Custom Hooks ✨

You can build your own Hooks to reuse logic.

Example: Tracking window width ⬇️

import { useState, useEffect } from "react";

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return width;
}

Now, useWindowWidth() can be used in multiple components.

🎯 Conclusion

Hooks have transformed the way developers write React code.

  • useState manages state.
  • useEffect handles side effects.
  • useContext, useRef, and useReducer provide advanced functionality.
  • Custom Hooks promote reusability.

By mastering Hooks, developers can build apps that are cleaner, more efficient, and easier to maintain.