DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Anxiny
Anxiny

Posted on • Updated on

Simple React Global State Management

Hi everyone!

I recently created my own solution for managing global state in my web app. It's working well so far, but I'm open to feedback and suggestions. I'm curious to know if there are any potential issues with my implementation, or if there are better ways to manage global state.

Thank you in advance for any input you might have!


import { useState, Dispatch, SetStateAction, useEffect, useId } from "react";

type Setter<T> = Dispatch<SetStateAction<T>> | ((value: T) => void)

/**
 * Create a pod with default value
 * @param value 
 * @returns usePod, value, updater
 */
export function createPod<T>(value: T) {
    const pod = {
        value: value
    };

    const setters: { [key in string]: Setter<T> } = {};

    const updater = (value: T) => {
        pod.value = value;
        for (let key in setters) {
            if (!setters.hasOwnProperty(key)) return;
            setters[key](value);
        }
    }

    const usePod = () => {
        const [value, setValue] = useState(pod.value);
        const key = useId()
        useEffect(() => {
            setters[key] = setValue;
            return () => {
                delete setters[key];
            }
        }, [])

        return [value, updater] as const
    }
    return [usePod, pod.value, updater] as const;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

12 APIs That You Will Love

Free and easy to use APIs for your next project, learning a new technology, or building a new feature.