DEV Community

Ghazi Khan
Ghazi Khan

Posted on

πŸš€ Elevate your React code modularity with Custom Hooks! 🎣

React Custom Hooks are a powerful tool that can take your component architecture to the next level! Swipe left to uncover the magic of creating reusable, modular logic that will simplify and supercharge your React components. πŸš€βœ¨

Today, we'll embark on an exciting journey by diving into a real-world example - the creation of a Dark Mode toggle! πŸ’»βœ¨

Code Example below the post.

πŸ’‘ Why Custom Hooks?

  • Reusability: Use your custom hooks across multiple components for consistent functionality.
  • Maintainability: Centralize complex logic in one place for easier maintenance.
  • Readability: Simplify component code by abstracting away intricate details into hooks.

πŸŒ™ Dark Mode Toggle: A Real-World Example

Dark Mode is not just a trendy design choice; it enhances user experience and reduces eye strain. With React Custom Hooks, implementing a Dark Mode toggle becomes a breeze. Let's break down the steps:

Step 1: Create a Custom Hook

// useDarkMode.js
import { useState, useEffect } from 'react';

const useDarkMode = () => {
  const [isDarkMode, setDarkMode] = useState(false);

  useEffect(() => {
    // Logic to toggle dark mode based on user preference or system settings
    // ...

    // For this example, let's use a simple toggle
  }, [isDarkMode]);

  return [isDarkMode, setDarkMode];
};

export default useDarkMode;
Enter fullscreen mode Exit fullscreen mode

Step 2: Use the Custom Hook in Your Component

// DarkModeToggle.js
import React from 'react';
import useDarkMode from './useDarkMode';

const DarkModeToggle = () => {
  const [isDarkMode, setDarkMode] = useDarkMode();

  return (
    <div>
      <label className="switch">
        <input type="checkbox" checked={isDarkMode} onChange={() => setDarkMode(!isDarkMode)} />
        <span className="slider round"></span>
      </label>
      <p>Enable Dark Mode</p>
    </div>
  );
};

export default DarkModeToggle;
Enter fullscreen mode Exit fullscreen mode

Step 3: Enjoy the Benefits
By using this custom hook, you've created a reusable Dark Mode toggle that can be easily integrated into any component. Plus, the logic for managing dark mode is neatly encapsulated in the useDarkMode hook, making your components cleaner and more maintainable.

In summary, React Custom Hooks are a game-changer. They empower you to build more scalable and maintainable React applications. What custom hooks have you created recently?
Share your experiences below! Let's level up our React game together! πŸ”₯πŸš€

Share this Instagram post with your friends and colleagues and learn collaboratively!

Top comments (0)