Earlier quoted context omitted.
My issue with React Context is you can only assign initial state through the `value` prop on the provider if you need that initial state to be derived from other hook state/data, which requires yet another wrapper component to pull those in. Even if you make a `createProvider` factory to initialize a `useMyContext` hook, it still requires what I mentioned above. Compare this to Vue's Pinia library where you can simpl…
You can use Tanstack Query or Zustand for this in React. They essentially have a global state, and you can attach reactive "views" to it. They also provide ways to delay rendering until you have the data ready. Your example would look like: const id = useState(...); const numericState = useState(0); const q = useQuery({ queryFn: async (context) => { const data = await fetch(..., {signal: context.signal}); const deriv…
Here's how Zustand gets around this, and lo-and-behold: it requires React Context :( [1] (Look at how much boilerplate is required!)
React Query at least gives you an `initialData` option [2] to populate the cache before anything is done, and it works similarly to `useState`'s initializer. The key nuance with `const [state, setState] = useState(myInitialValue)` is the initial value is set on `state` before anything renders, so you don't need to wait while the component flashes `null` or a loading state. Whatever you need it to be is there immediately, helping UIs feel faster. It's a minor detail, but it makes a big difference when you're working with more complex dependencies.
1. https://zustand.docs.pmnd.rs/guides/initialize-state-with-pr...
2. https://tanstack.com/query/v5/docs/framework/react/guides/in...
---
I guess I could abuse React Query like this...
function useGlobalStore() {
const myHookState = useMyHook(); // not async
return useQuery({
initialData: {
optionA: true,
optionB: myHookState,
}
});
}
And you'd have to use `queryClient` to mutate the state locally since we aren't dealing with server data here.But here's what I really want from the React team...
// Hook uses global instance instead of creating a new one each time it's used. No React Context boilerplate or ceremony. No wrapping components with more messy JSX. I can set state using React's primitives instead of messing with a 3rd party store:
const useGlobalStore = createGlobalStore(() => {
const dataFromAnotherHook = useAnotherHook();
const [settings, setSettings] = useState({
optionA: true,
optionB: dataFromAnotherHook,
});
return {
settings,
setSettings,
}
});