DEV Community

Cover image for How to Optimize State Management with React Custom Hook: useStorage Explained
GihanRangana
GihanRangana

Posted on

How to Optimize State Management with React Custom Hook: useStorage Explained

In this video, we dive into a powerful React custom hook called "useStorage" that can revolutionize your state management. State management is a crucial aspect of any React application, and with the useStorage hook, we can optimize it to the next level.

With "useStorage," you'll learn how to efficiently save and retrieve data from the browser's local storage. This hook allows you to persist state across page refreshes, ensuring a seamless user experience.

We'll explore the implementation details of "useStorage" and its various use cases. Additionally, you'll discover how to handle edge cases and potential pitfalls when working with local storage in React.

By leveraging this custom hook, you can simplify your codebase, enhance performance, and improve overall user satisfaction. Say goodbye to cumbersome state management techniques and welcome the simplicity of "useStorage."

Join us in this informative and practical tutorial to unlock the true potential of React's state management capabilities. Don't miss out on the opportunity to optimize your state management with the incredible "useStorage" custom hook!

useStorage Hook

import { useState, useEffect, useCallback } from 'react';

const useStorage = (key: string, defaultValue: number | string | null = null, type?: "local" | "session") => {

    const storage = type === "local" ? window.localStorage : type === "session" ? window.sessionStorage : undefined;

    const [value, setValue] = useState<any>(() => {

        console.log(storage);

        const storageValue = storage?.getItem(key)

        if (storageValue != null) return JSON.parse(storageValue);

        return defaultValue;
    })

    useEffect(() => {

        if (value === undefined) return storage?.removeItem(key)

        storage?.setItem(key, JSON.stringify(value))

    }, [key, value, storage])

    const remove = useCallback(() => {
        setValue(undefined)
    }, [])

    return [value, setValue, remove]

}

export default useStorage;
Enter fullscreen mode Exit fullscreen mode

Usage

import React, { useEffect } from 'react';
import useStorage from '../hooks/useStorage';

const UseStorageComponent: React.FC<UseStorageComponentProps> = (props) => {

    const [local, setLocal, removeLocal] = useStorage("firstName", "Coders", "local")
    const [session, setSession, removeSession] = useStorage("lastName", "Life", "session")

    useEffect(() => {
        console.log("local", local);
        console.log("session", session);

    }, [local, session])

    return (
        <>
            <div>
                <button
                    onClick={() => {
                        setLocal("updatedLocal")
                    }}
                >
                    Set Local Storage Value
                </button>

                <button
                    onClick={() => {
                        setSession("sessionUpdated")
                    }}
                >
                    Set Session Storage Value
                </button>
            </div>

            <div>

                <p>Local Storage Value: {local}</p>
                <p>Session Storage Value: {session}</p>

            </div>

            <div style={{ marginTop: 10 }}>
                <button
                    onClick={removeLocal}
                >
                    Remove Local Value
                </button>

                <button
                    onClick={removeSession}
                >
                    Remove Session Value
                </button>
            </div>
        </>
    )
}

interface UseStorageComponentProps {
    [key: string]: any
}

export default UseStorageComponent;
Enter fullscreen mode Exit fullscreen mode

🧑‍💻 Source: https://github.com/TheCodersLife/reactjs-custom-hooks

Top comments (0)