|
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 simply create a global (setup) hook that allows you to bring in other hooks and dependencies, and return the final, global state. Then when you use it, it points to a global instance instead of creating unique instances for each hook used. Example (React cannot do this, not without enormous boilerplate and TypeScript spaghetti -- good luck!): export const useMyStore = defineStore("myStore", () => {
const numericState = ref(0);
const computedState = computed(() => reactiveState.value * 2);
const numberFromAnotherHook = useAnotherHook();
const { data, error, loading } = useFetch(...);
const derivedAsyncState = computed(() => {
return data.value + numericState.value + numberFromAnotherHook.value;
});
return {
numericState,
computedState,
numberFromAnotherHook,
derivedAsyncState,
}
});
This is remarkably easy, and the best part is: I don't have to wrap my components with another <Context.Provider> component. I can... just use the hook! I sorely wish React offered a better way to wire up global or shared state like this. React doesn't even have a plugin system that would allow someone to port Pinia over to React. It's baffling.Every other 3rd party state management library has to use React Context to initialize store data based on other React-based state/data. Without Context, you must wait for a full render cycle and assign the state using `useEffect`, causing your components to flash or delay rendering before the store's ready. |
Your example would look like:
It'll handle cancellation if your state changes while the query is being evaluated, you can add deferred rendering, and so on. You can even hook it into Suspense and have "transparent" handling of in-progress queries.The downside is that mutations also need to be handled by these libraries, so it essentially becomes isomorphic to Solid's signals.