DEV Community

Cover image for What Are React Hooks? A Beginner-Friendly Guide with Examples
JSXJunkie
JSXJunkie

Posted on

What Are React Hooks? A Beginner-Friendly Guide with Examples

πŸ‘‹ Introduction
When I first started learning React, I kept hearing about something called "Hooks" β€” and how they changed the way we write components forever.

So what exactly are React Hooks?
And why do we even need them?

Let’s break it down in simple terms β€” with real-world examples.

🧠 What Are Hooks?
Hooks are special functions that let you "hook into" React features like:

State (useState)

Lifecycle (useEffect)

Context (useContext)

Refs (useRef)

Memoization (useMemo, useCallback)

They work only in functional components and eliminate the need for class-based components in most cases.

βœ… Why Hooks?
Before hooks, we needed class components to manage state and lifecycle methods. Now, thanks to hooks, you can write everything using simple functional components.

Benefits:

Less boilerplate

Easier to read and reuse

No this keyword mess

πŸ” Commonly Used Hooks
1️⃣ useState β€” Add State to Functional Components

import { useState } from 'react';

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

2️⃣ useEffect β€” Run Side Effects (like API calls, timers, etc.)

import { useEffect, useState } from 'react';

function Posts() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(res => res.json())
      .then(data => setPosts(data));
  }, []); // Run once on mount

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

3️⃣ useRef β€” Refer to DOM elements or persist values

import { useRef } from 'react';

function InputFocus() {
  const inputRef = useRef();

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

  return (
    <>
      <input ref={inputRef} placeholder="Click the button to focus" />
      <button onClick={handleFocus}>Focus Input</button>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

4️⃣ useContext β€” Consume Global Context Without Props

import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function ThemedButton() {
  const theme = useContext(ThemeContext);

  return (
    <button className={`bg-${theme}-500 text-white`}>Theme Button</button>
  );
}
Enter fullscreen mode Exit fullscreen mode

5️⃣ useMemo β€” Optimize Performance for Expensive Calculations

import { useMemo, useState } from 'react';

function ExpensiveCalculation({ number }) {
  const [multiplier, setMultiplier] = useState(2);

  const result = useMemo(() => {
    console.log('Calculating...');
    return number * multiplier;
  }, [number, multiplier]);

  return <p>Result: {result}</p>;
}
Enter fullscreen mode Exit fullscreen mode

6️⃣ useCallback β€” Memoize Functions

const handleClick = useCallback(() => {
  console.log('Button clicked');
}, []);
Enter fullscreen mode Exit fullscreen mode

βœ… Useful when passing functions to child components (prevents re-renders)

πŸš€ Bonus: Custom Hooks
You can create your own hooks to reuse logic:

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;
}
Enter fullscreen mode Exit fullscreen mode

πŸ”’ Rules of Hooks
βœ… Always use hooks at the top level (no conditions/loops)

βœ… Only call hooks inside React functions (not regular JS functions)

🧠 When to Use Which Hook?
Goal Hook
Add local state useState
Run side effects (fetch) useEffect
Access DOM elements useRef
Use global context useContext
Optimize performance useMemo
Memoize event handlers useCallback
Share logic across components Custom Hooks

πŸ§‘β€πŸ’» Final Thoughts
Hooks made React cleaner, simpler, and more powerful.
They’re now the standard way to build modern React apps β€” and once you get comfortable with them, you’ll wonder how you ever wrote React without them.

πŸ’¬ What’s Next?
Want to learn real-world use cases for each hook?
Follow me β€” I’ll be posting deep dives into each React Hook with project examples, performance tips, and best practices.

Top comments (0)