DEV Community

Cover image for πŸ“Œ Top 10 React.js Hooks You Must Know (With Examples) πŸš€
Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

4 2 2 2 2

πŸ“Œ Top 10 React.js Hooks You Must Know (With Examples) πŸš€

Read the full article on Medium and show some support!


1. useState – Managing Component State

The useState hook lets you add state to functional components. It returns a state variable and a function to update it.

Example:

import { useState } from "react";

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

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

Use Cases:

  • Managing form inputs
  • Handling UI toggles (like modals, themes, etc.)
  • Tracking user interactions

2. useEffect – Handling Side Effects

useEffect is used to perform side effects like fetching data, updating the DOM, and setting up event listeners.

Example:

import { useState, useEffect } from "react";

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

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(response => response.json())
      .then(data => setData(data));

  }, []); // Empty dependency array means it runs only once (on mount)

  return (
    <ul>
      {data.map(post => <li key={post.id}>{post.title}</li>)}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

Use Cases:

  • Fetching API data
  • Handling event listeners
  • Managing subscriptions

3. useContext – Accessing Global State

The useContext hook allows components to consume values from a React Context without prop drilling.

Example:

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

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

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedComponent />
    </ThemeContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Use Cases:

  • Managing global themes
  • Sharing authentication state
  • Avoiding prop drilling

4. useRef – Accessing DOM Elements & Persistent Values

The useRef hook provides a way to reference a DOM element directly or persist values between renders without causing re-renders.

Example:

import { useRef } from "react";

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

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

Use Cases:

  • Managing uncontrolled form inputs
  • Keeping track of previous values
  • Storing timers

5. useReducer – Complex State Management

useReducer is an alternative to useState for managing complex state logic.

Example:

import { useReducer } from "react";

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, { 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

Use Cases:

  • Handling complex state logic
  • Managing state transitions
  • Working with useContext for global state

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay