-
Is there a way to store a value in an atom such that it's always guaranteed to be up-to-date and there's no delay in setting it? I have some code that I want to move to Recoil because of performance reasons (everything gets rerendered all the time). Here is a much simplified version: // MyComponent1
const queryResult = useQuery(/* some Apollo stuff */);
if (!queryResult.data) return null;
return <MyComponent2 data={queryResult.data} />;
// MyComponent2
const transformedData = useMemo(() => expensiveTransformation(data), [data]);
const someMethodsAndStuff = useSomeHook(transformedData);
return <MyContext.Provider value={{ someMethodsAndStuff }}>/* some children */</MyContext.Provider>;
// MyComponent3
const { someMethodThatUsesData } = useContext(MyContext); The advantage of this solution is that What's the best pattern for dealing with this? Frankly, I hoped there would be something like:
Or if this doesn't fit the purpose of atoms, then another way of thinking about this could be that we can create a selector that mirrors a value and provides a pass-through from React to Recoil. Edit: I've been thinking about this, and it probably could not work frictionlessly like I imagined. Props and even contexts are values passed down the tree, but the Recoil state is global. So if we changed it mid-render, which is essentially what I wanted, we could end up with inconsistent results on the screen. However, what would be the preferred solution then? I guess the thing that bothers me is that I don't want to add even more null checks. Something I enjoyed about contexts is that you can be sure the value is there. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Async data could be used as an input to the data-flow graph via a selector. You could also use Atom Effects to subscribe to some external value change and update an atom. In either case you can have derived selectors which will be updated automatically. However, if your external value is obtained via a React hook, then neither of these approaches will work as you cannot use hooks from within a selector or effect. In that case |
Beta Was this translation helpful? Give feedback.
Async data could be used as an input to the data-flow graph via a selector. You could also use Atom Effects to subscribe to some external value change and update an atom. In either case you can have derived selectors which will be updated automatically. However, if your external value is obtained via a React hook, then neither of these approaches will work as you cannot use hooks from within a selector or effect. In that case
useEffect()
can be used by some component just for the purposes of keeping the external state in sync with an atom. Note that we are currently working on an optimization that will issue re-renders earlier for state updates which may possibly help reducing your latenc…