How to use the useLocalStorage hook for persisting theme preferences in Next.js



Image not found!!

To use the useLocalStorage hook for persisting theme preferences in a Next.js application, you'll first need to install the use-local-storage package if you haven't already. Then you can create a custom hook that utilizes this package. Here's how you can do it:

  1. Install the use-local-storage package:
bash
npm install use-local-storage
  1. Create a custom hook for managing theme preferences:
javascript
// utils/useTheme.js import { useState } from 'react'; import useLocalStorage from 'use-local-storage'; export const useTheme = () => { const [storedTheme, setStoredTheme] = useLocalStorage('theme'); const [theme, setTheme] = useState(storedTheme || 'light'); const toggleTheme = () => { const newTheme = theme === 'light' ? 'dark' : 'light'; setTheme(newTheme); setStoredTheme(newTheme); }; return [theme, toggleTheme]; };
  1. Now you can use this custom hook in your components to manage the theme preferences:
javascript
// components/ThemeToggle.js import React from 'react'; import { useTheme } from '../utils/useTheme'; const ThemeToggle = () => { const [theme, toggleTheme] = useTheme(); return ( <button onClick={toggleTheme}> {theme === 'light' ? 'Switch to Dark Mode' : 'Switch to Light Mode'} </button> ); }; export default ThemeToggle;
  1. Finally, integrate the ThemeToggle component into your Next.js application where needed.

This setup will ensure that the user's theme preference is stored in local storage and persists across page refreshes. The useLocalStorage hook handles the local storage part, and the useTheme custom hook abstracts the logic for managing theme preferences.