DEV Community

Anxiny
Anxiny

Posted on • Edited 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

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay