RFC: useGlobalState
This is the global state implemented using batch updates. The usage is similar to useState, simpler than context, and the usage scenarios are different.
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
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?
See react-use createGlobalState.
@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.
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>
);
}
@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.