How to create a custom hook for handling dark mode preferences in Next.js



Image not found!!

Creating a custom hook for handling dark mode preferences in Next.js involves a few steps. You'll need to manage the state, update the UI based on the dark mode state, and persist the dark mode preference. Here's a step-by-step guide:

  1. Create a new file for your custom hook: Create a new file, let's say useDarkMode.js in your hooks directory.

  2. Import necessary dependencies: In your useDarkMode.js file, import useState from React and any other dependencies you might need.

    jsx
    import { useState } from 'react';
  3. Create the hook: Define your custom hook, initialize the dark mode state, and create functions to toggle the dark mode and persist the preference.

    jsx
    import { useState, useEffect } from 'react'; const useDarkMode = () => { const [isDarkMode, setIsDarkMode] = useState(false); const toggleDarkMode = () => { setIsDarkMode((prevMode) => !prevMode); }; useEffect(() => { // Update UI or apply changes when dark mode state changes // For example, you can add/remove a class to the body element document.body.classList.toggle('dark-mode', isDarkMode); // Persist dark mode preference to localStorage localStorage.setItem('darkMode', JSON.stringify(isDarkMode)); }, [isDarkMode]); // Load dark mode preference from localStorage on initial render useEffect(() => { const storedDarkMode = localStorage.getItem('darkMode'); if (storedDarkMode) { setIsDarkMode(JSON.parse(storedDarkMode)); } }, []); return { isDarkMode, toggleDarkMode }; }; export default useDarkMode;
  4. Implement in your Next.js components: Import and use the useDarkMode hook in your Next.js components.

    jsx
    import React from 'react'; import useDarkMode from '../hooks/useDarkMode'; const YourComponent = () => { const { isDarkMode, toggleDarkMode } = useDarkMode(); return ( <div> <button onClick={toggleDarkMode}> Toggle Dark Mode </button> <p>{isDarkMode ? 'Dark Mode Enabled' : 'Light Mode Enabled'}</p> {/* Your component content here */} </div> ); }; export default YourComponent;
  5. Styles (optional): You might want to add styles for dark mode in your CSS. For example, in a global CSS file:

    css
    body.dark-mode { background-color: #1a1a1a; color: #ffffff; /* Add more styles for dark mode here */ }

    Make sure to import the CSS file in your Next.js app.

Now, your Next.js app should have a working dark mode implementation using the custom hook.