DEV Community

Mahesh Galange
Mahesh Galange

Posted on

2 1 1 1

Mastering Custom Hooks in React – A Beginner’s Guide 🪝

📌 Table of Contents

  1. What Are Custom Hooks?
  2. Why Use Custom Hooks?
  3. How to Create One – Example
  4. Best Practices & Common Mistakes

🧠 What Are Custom Hooks?

Custom Hooks are JavaScript functions that start with the word use and allow you to extract component logic into reusable functions. They use React’s built-in hooks (like useState, useEffect) under the hood and follow the same rules.

🔍 Why Use Custom Hooks?
Here’s what you gain:

  • ♻️ Reusability: Share logic across multiple components
  • 🧼 Cleaner Code: Keep your components focused on UI
  • 🧩 Composability: Combine multiple hooks into one

💡 How to Create One – Example

Let’s create a custom hook called useLocalStorage.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}
Enter fullscreen mode Exit fullscreen mode

✅ Usage:

function ThemeToggle() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Switch to {theme === 'light' ? 'dark' : 'light'} mode
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

✨ Final Thoughts

That’s a wrap on custom hooks! They’re powerful, reusable, and help keep your code clean and modular. I hope this guide helps you create your own and apply them confidently in your React projects.

This was my first blog—if you liked it or found it helpful, feel free to connect or share your feedback!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay