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:
use-local-storage
package:bashnpm install use-local-storage
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];
};
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;
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.