How to use the useLocalStorage hook for persistent theme settings in Next.js



Image not found!!

To use the useLocalStorage hook for persistent theme settings in a Next.js application, you'll first need to create the useLocalStorage hook or use an existing library that provides it. This hook allows you to easily interact with the browser's localStorage API. Below is an example implementation of the useLocalStorage hook:

jsx
// useLocalStorage.js import { useState } from 'react'; const useLocalStorage = (key, initialValue) => { // Get stored value from local storage on initial render const storedValue = typeof window !== 'undefined' ? JSON.parse(localStorage.getItem(key)) || initialValue : initialValue; // State to hold the current value const [value, setValue] = useState(storedValue); // Function to update both state and local storage const updateValue = (newValue) => { setValue(newValue); localStorage.setItem(key, JSON.stringify(newValue)); }; return [value, updateValue]; }; export default useLocalStorage;

Now, you can use this hook in your Next.js component to manage persistent theme settings. Below is an example of how you might use it:

jsx
// ThemeSwitcher.js import React from 'react'; import useLocalStorage from '../path/to/useLocalStorage'; const ThemeSwitcher = () => { // Initialize the theme setting with a default value const [theme, setTheme] = useLocalStorage('theme', 'light'); const toggleTheme = () => { // Toggle between 'light' and 'dark' const newTheme = theme === 'light' ? 'dark' : 'light'; setTheme(newTheme); }; return ( <div> <p>Current Theme: {theme}</p> <button onClick={toggleTheme}>Toggle Theme</button> </div> ); }; export default ThemeSwitcher;

In this example, the useLocalStorage hook is used to store and retrieve the current theme setting from the localStorage. The theme is initially set to 'light', and a button allows the user to toggle between 'light' and 'dark' themes. The selected theme is stored in the localStorage, making it persistent across page reloads.

Make sure to import and use this ThemeSwitcher component in your Next.js pages or layout components to enable persistent theme settings.