Skip to main content

Command Palette

Search for a command to run...

What are React Hooks ??

The Ultimate Guide for Beginners

Updated
โ€ข4 min read
What are React Hooks ??

React Hooks allow you to use state and lifecycle features in functional components without writing class components. Introduced in React 16.8, Hooks make React development more efficient and readable.

Letโ€™s break down the most important Hooks and how to use them! ๐Ÿ‘‡


๐Ÿ”น 1. useState โ€“ Managing State

๐Ÿ“Œ useState lets you add state inside a functional component.

Example: Counter App

import { useState } from "react";

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

๐Ÿ”น How it works?

  • count โ†’ Holds the state value

  • setCount โ†’ Updates the state

  • useState(0) โ†’ Initializes count to 0


๐Ÿ”น 2. useEffect โ€“ Side Effects in Components

๐Ÿ“Œ useEffect runs after the component renders. It's used for fetching data, updating the DOM, or setting up event listeners.

Example: Fetching Data

import { useState, useEffect } from "react";

export default function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((data) => setUsers(data));
  }, []); // Empty array means it runs only on mount

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

๐Ÿ”น How it works?

  • Runs once when the component mounts (because of [])

  • Calls API and updates users state

Variants of useEffect:

  • useEffect(() => { ... }) โ†’ Runs on every render

  • useEffect(() => { ... }, []) โ†’ Runs only once (on mount)

  • useEffect(() => { ... }, [count]) โ†’ Runs when count changes


๐Ÿ”น 3. useRef โ€“ Accessing DOM Elements & Preserving Values

๐Ÿ“Œ useRef is used for getting a reference to a DOM element or storing values without causing re-renders.

Example: Focusing an Input

import { useRef, useEffect } from "react";

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

  useEffect(() => {
    inputRef.current.focus(); // Auto-focus input field on mount
  }, []);

  return <input ref={inputRef} type="text" placeholder="Type here..." />;
}

๐Ÿ”น How it works?

  • useRef(null) โ†’ Creates a mutable reference

  • inputRef.current โ†’ Directly accesses the input


๐Ÿ”น 4. useCallback โ€“ Optimizing Functions

๐Ÿ“Œ useCallback memoizes functions so they donโ€™t get re-created on every render, improving performance.

Example: Avoid Unnecessary Re-renders

import { useState, useCallback } from "react";

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

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

๐Ÿ”น Why use useCallback?

  • Prevents increment from recreating on each render

  • Improves performance in child components


๐Ÿ”น 5. useMemo โ€“ Optimizing Expensive Calculations

๐Ÿ“Œ useMemo caches a computed value so it doesnโ€™t re-calculate unnecessarily.

Example: Expensive Calculation

import { useState, useMemo } from "react";

export default function ExpensiveCalculation() {
  const [number, setNumber] = useState(0);

  const squared = useMemo(() => {
    console.log("Calculating square...");
    return number * number;
  }, [number]);

  return (
    <div>
      <h1>Square: {squared}</h1>
      <button onClick={() => setNumber((prev) => prev + 1)}>Increase</button>
    </div>
  );
}

๐Ÿ”น How it works?

  • Only re-computes when number changes

  • Avoids unnecessary calculations


๐Ÿ”น 6. useContext โ€“ Global State Management

๐Ÿ“Œ useContext helps share global state without prop drilling.

Example: Theme Context

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

export function ThemeProvider({ children }) {
  return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>;
}

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

๐Ÿ”น Why use useContext?

  • Avoids prop drilling

  • Shares state across multiple components


๐Ÿ“Œ Other Useful Hooks

  • useReducer โ†’ Like useState, but for complex state logic

  • useImperativeHandle โ†’ Exposes methods from a child component

  • useLayoutEffect โ†’ Like useEffect, but runs before the screen updates


๐ŸŽฏ Final Thoughts

Hooks simplify React development by making functional components more powerful. Mastering them will help you write cleaner, reusable, and optimized React apps!

๐Ÿ’ก Now, go build something amazing with React Hooks! ๐Ÿš€


Got questions? Drop them below! โฌ‡๏ธ Happy coding! ๐ŸŽ‰