rfcs icon indicating copy to clipboard operation
rfcs copied to clipboard

RFC: useGlobalState

Open mushan0x0 opened this issue 3 years ago • 6 comments

This is the global state implemented using batch updates. The usage is similar to useState, simpler than context, and the usage scenarios are different.

Here is my implementation and usage example.

mushan0x0 avatar Aug 25 '22 13:08 mushan0x0

Why not have the keys be Symbols? That would mean you basically couldn't conflict. The downside is that you would have to import the Symbol from another module or make a wrapper hook and import it, however, I think this is really a plus not a downside as it makes it so much clearer where the state sharing is

Zachiah avatar Oct 22 '22 15:10 Zachiah

I had a similar but a slightly different approach. Check my implementation of useSync().

Do you think that it is worth creating an RFC for?

iMrDJAi avatar Aug 11 '23 23:08 iMrDJAi

See react-use createGlobalState.

wmzy avatar Aug 15 '23 00:08 wmzy

@wmzy You'll still have to import the hook into different components in order to use it, which is not ideal. A subscription based one with a unique identifier (either a string or a symbol) will be way handier and will cause less headache when trying to remember which hook to import and where to import it from.

iMrDJAi avatar Aug 16 '23 09:08 iMrDJAi

Libraries like feature-state, jotai, and nanostores already provide implementations for creating global states.

How would useGlobalState() differ?

Example using feature-state (< 1KB minified)

store/tasks.ts

import { createState } from 'feature-state';

export const $tasks = createState<Task[]>([]);

export function addTask(task: Task) {
    $tasks.set([...$tasks.get(), task]);
}

components/Tasks.tsx

import { useGlobalState } from 'feature-state-react';
import { $tasks } from '../store/tasks';

export const Tasks = () => {
    const tasks = useGlobalState($tasks);

    return (
        <ul>
            {tasks.map(task => <li key={task.id}>{task.title}</li>)}
        </ul>
    );
}

bennobuilder avatar Jun 06 '24 09:06 bennobuilder

@bennoinbeta And why going for third party solutions if React already had this built-in? Given how crucial this is and how simple it is to implement, it makes sense to have it included in core.

iMrDJAi avatar Jun 06 '24 20:06 iMrDJAi