🚀 AI SaaS Starter is now live!

Start building your SaaS in a Day

50% OFF

Use code FIRST50

Blog/NotesConcept

Implement useSessionStorage Custom Hook in React [Interview]

Understand the code implementation of useSessionStorage custom hook in react that will help to efficiently manager session storage in application.

Intermediate

Anuj Sharma

Last Updated Nov 10, 2025


useLocalStorage and useSessionStorage is most widely used custom hooks to simplify the interaction with localStorage and sessionStorage at the application level and provide a clean way for interaction.

In this blog, Let's understand the implementation code of useSessionStorage custom hook in react.

How to Approach

While exploring the approach, its important to know that useSessionStorage custom hook in react will internally going to use the window.sessionStorage object only, and convert the object into string using JSON.stringify() function.

As part of the custom hook, we need to handle the set and get the session storage values, and introduce error handing at the common place under useSessionStorage custom hook, to handle any runtime errors.

Implementation of useSessionStorage Custom Hook

Let's checkout the code implementation and explanation of the useSessionStorage hook.

Custom Hook Code

import { useState } from 'react';

const useSessionStorage = (key, initialValue) => {
    const [storedValue, setStoredValue] = useState(() => {
        try {
            const item = window.sessionStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            console.error(error);
            return initialValue;
        }
    });

    const setValue = (value) => {
        try {
            setStoredValue(value);
            window.sessionStorage.setItem(key, JSON.stringify(value));
        } catch (error) {
            console.error(error);
        }
    };

    return [storedValue, setValue];
};

export default useSessionStorage;

Step by Step Code Explanation

  1. useSessionStorage Function: Define the custom hook function that takes two parameters, key (for sessionStorage key) and initialValue.
  2. storedValue: Initialize state using useState and try to retrieve the value from sessionStorage based on the provided key. If no value is found, the initialValue is used.
  3. setValue Function: Define a function to update the storedValue in state and synchronize the sessionStorage with the new value.
  4. Return: Return an array containing storedValue and setValue to be used in components.

Understand useSessionStorage Hook Usage

Let's understand the useSessionStorage usage with a simple example of setting the useName key in the session storage.

import React from 'react';
import useSessionStorage from './useSessionStorage';

const App = () => {
    const [name, setName] = useSessionStorage('userName', 'Guest');

    const handleNameChange = (e) => {
        setName(e.target.value);
    };

    return (
        <div>
            <input type="text" value={name} onChange={handleNameChange} />
            <p>Hello, {name}!</p>
        </div>
    );
};

export default App; 

In this example, we import the useSessionStorage custom hook and use it to manage the 'userName' key in sessionStorage with a default value of 'Guest'. We then update the name value based on user input in an input field.

Further Reading

  1. Top 20 Most Asked Custom Hooks in React
  2. Understand JavaScript localStorage & sessionStorage

Share this post now:

💬 Comments (0)

Login to comment

Flaunt You Expertise/Knowledge & Help your Peers

Sharing your knowledge will strengthen your expertise on topic. Consider writing a quick Blog/Notes to help frontend folks to ace Frontend Interviews.

Other Related Blogs

Top 10 React Performance Optimization Techniques [React Interview]

Anuj Sharma

Last Updated Nov 10, 2025

Find the top React Performance Optimization Techniques specific to React applications that help to make your react app faster and more responsive for the users along with some bonus techniques.

Polyfill for map, filter, and reduce in JavaScript

Anuj Sharma

Last Updated Oct 2, 2025

Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.

Master Hoisting in JavaScript with 5 Examples

Alok Kumar Giri

Last Updated Jun 2, 2025

Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.

Implement useFetch() Custom Hook in React (Interview)

Anuj Sharma

Last Updated Nov 10, 2025

Find the step-by-step explanation of the useFetch custom hook in React that helps in fetching the data from an API and handling loading, error states.

Implement Infinite Currying Sum: JavaScript Interview Question sum(1)(2)(3)

Anuj Sharma

Last Updated Nov 8, 2025

In this post, we will going to cover the step-by-step implementation of Infinite Currying Sum with a code example. This is one of the most common JavaScript Interview questions.

setTimeout Polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Aug 3, 2025

Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.

Stay Updated

Subscribe to FrontendGeek Hub for the frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

© 2024 FrontendGeek. All rights reserved