How to create a custom hook for handling session storage in Next.js



Image not found!!

In Next.js, you can create a custom hook for handling session storage by using the useEffect and useState hooks provided by React. Here's a simple example of a custom hook for managing session storage:

jsx
import { useState, useEffect } from 'react'; const useSessionStorage = (key, initialValue) => { // Get data from session storage on component mount const storedValue = sessionStorage.getItem(key); const initial = storedValue ? JSON.parse(storedValue) : initialValue; // State to hold the current value const [value, setValue] = useState(initial); // Update session storage whenever the value changes useEffect(() => { sessionStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; }; export default useSessionStorage;

Now you can use this hook in your Next.js components. Here's an example:

jsx
import React from 'react'; import useSessionStorage from '../path-to-useSessionStorage'; const ExampleComponent = () => { // Usage of custom hook const [sessionValue, setSessionValue] = useSessionStorage('myKey', 'defaultValue'); const handleButtonClick = () => { // Update the session storage value setSessionValue('new value'); }; return ( <div> <p>Session Storage Value: {sessionValue}</p> <button onClick={handleButtonClick}>Update Session Storage</button> </div> ); }; export default ExampleComponent;

In this example, useSessionStorage is a custom hook that takes a key and an initial value as arguments. It returns an array with the current value from session storage and a function to update that value. The session storage is updated whenever the value changes using the useEffect hook.