DEV Community

Suman Bhattarai
Suman Bhattarai

Posted on

πŸš€ Mastering React Hooks: The Ultimate Guide (With Examples!)

React Hooks have revolutionized how we write functional components, eliminating the need for class components while making state management and side effects more intuitive. In this guide, we'll explore all React Hooks, including the latest ones, with examples to help you integrate them effectively into your projects. 🎯


πŸ“Œ What Are React Hooks?

React Hooks are built-in functions that allow functional components to use state and lifecycle features without converting them into class components. They make React code cleaner, reusable, and easier to test. πŸŽ‰


πŸ† Essential React Hooks

1️⃣ useState - Manage Component State πŸ—οΈ

The useState hook allows you to manage local state inside functional components.

import React, { useState } from "react";

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

2️⃣ useEffect - Handle Side Effects ⚑

The useEffect hook is used for side effects such as fetching data, subscriptions, or updating the DOM.

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

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

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

    return () => clearInterval(interval);
  }, []);

  return <p>Elapsed time: {seconds}s</p>;
};
Enter fullscreen mode Exit fullscreen mode

3️⃣ useContext - Share State Globally 🌍

The useContext hook provides a way to consume context in functional components without prop drilling.

import React, { createContext, useContext } from "react";

const ThemeContext = createContext("light");

const ThemeSwitcher = () => {
  const theme = useContext(ThemeContext);
  return <p>Current theme: {theme}</p>;
};

const App = () => (
  <ThemeContext.Provider value="dark">
    <ThemeSwitcher />
  </ThemeContext.Provider>
);
Enter fullscreen mode Exit fullscreen mode

🎯 Advanced React Hooks

4️⃣ useReducer - Manage Complex State πŸ—οΈ

The useReducer hook is an alternative to useState, useful for managing complex state logic.

import React, { useReducer } from "react";

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

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

5️⃣ useRef - Access DOM Elements πŸ“Œ

The useRef hook creates a mutable reference that persists across renders. It's commonly used to access DOM elements directly.

import React, { useRef } from "react";

const FocusInput = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

6️⃣ useMemo - Optimize Performance πŸš€

The useMemo hook memoizes a computed value, preventing unnecessary recalculations.

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

const ExpensiveCalculation = ({ num }) => {
  const computedValue = useMemo(() => {
    return num * 2; // Simulating heavy computation
  }, [num]);

  return <p>Computed Value: {computedValue}</p>;
};
Enter fullscreen mode Exit fullscreen mode

7️⃣ useCallback - Optimize Functions πŸ“Œ

The useCallback hook memoizes functions to prevent unnecessary re-renders.

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

const Button = React.memo(({ handleClick }) => {
  console.log("Button re-rendered");
  return <button onClick={handleClick}>Click Me</button>;
});

const App = () => {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prev) => prev + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <Button handleClick={increment} />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ Newest React Hooks (React 18+)

8️⃣ useId - Unique IDs πŸ†”

useId generates unique IDs for accessibility attributes.

import { useId } from "react";

const Form = () => {
  const id = useId();
  return (
    <div>
      <label htmlFor={id}>Enter Name:</label>
      <input id={id} type="text" />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

🎯 Conclusion

React Hooks provide powerful capabilities to manage state, optimize performance, and handle side effects in functional components. By leveraging hooks like useState, useEffect, useMemo, and useCallback, you can write more efficient and maintainable React applications! πŸš€πŸ”₯

Which React Hook do you use the most? Let me know in the comments! πŸ’¬


πŸ“ Happy Coding! πŸŽ‰

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term contextβ€”plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project

πŸ”₯ Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video πŸŽ₯

πŸ‘‹ Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creatorsβ€”let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay