reatomUseContext #797
8000
artalar
started this conversation in
Ideas
Replies: 1 comment
-
Example of code, that I am writing without this feature: import { withStatusesAtom, withErrorAtom, withDataAtom, reatomAsync, withAbort, atom } from "@reatom/framework";
import { fetchUserProfile } from "@/api";
export function createUserProfileModel() {
const fetchUserProfileAction = reatomAsync(async (ctx) => {
const profile = await ctx.schedule(() => fetchUserProfile({ controller: ctx.controller }));
return {
...profile,
context: {
jobDescriptionAtom: atom(profile.context.cv, "jobDescriptionAtom"),
cvAtom: atom(profile.context.job_description, "cvAtom"),
},
};
}, "fetchUserProfileAction").pipe(withDataAtom(), withAbort(), withErrorAtom(), withStatusesAtom());
return {
fetchUserProfileAction,
};
} import type { ReactNode } from "@tanstack/react-router";
import { createContext, useMemo } from "react";
import { createUserProfileModel } from "./user-profile-model";
export const UserProfileModelContext = createContext<ReturnType<typeof createUserProfileModel> | null>(null);
export function UserProfileModelProvider({ children }: { children: ReactNode }) {
const userProfileModel = useMemo(() => createUserProfileModel(), []);
return <UserProfileModelContext.Provider value={userProfileModel}>{children}</UserProfileModelContext.Provider>;
} import { useContext } from "react";
import { UserProfileModelContext } from "./user-profile-context";
export function useUserProfileModel() {
const userProfileModel = useContext(UserProfileModelContext);
if (userProfileModel === null) {
throw new Error("useContext must be used within a UserProfileModelProvider");
}
return userProfileModel;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
In the React world, it is a common pattern and the main mindset to bind a state lifetime to a component lifetime. It is a good pattern because of its obvious memory management benefits - all data is automatically cleared on unmount.
If you are trying to use this pattern with Reatom (or any other global state manager), you could have a set of confusions: you need to use
useAtom
with a primitive and share the created atom via props, which could take a lot of boilerplate - prop drilling and extra explicit type definitions for all props of intermediate components. Or, you should create a context and manage the whole thing yourself.To simplify this case, I propose a new method
reatomUseContext
with a couple of handy overloads, which is creates an atom for the provider mount and destroy it on unmount.Of course it should be possible to use
reatomUseContext
for a whole model creation.Beta Was this translation helpful? Give feedback.
All reactions