Search code examples
reactjsstaterecoiljs

React / Recoil - when is setAtom new value available?


I'm trying to understand React Recoil and when an updated atom's value is available, or how to make the new value propagate vertically and horizontally across the app.

For example if I have an atom called userState and I update one of its properties like avatar_url, the value is not the new value if I console it right after the setUser.

const [user, setUser] = useRecoilState(userState);

setUser({ avatar_url: imageURL, ...appUser});

console.log(imageURL); // is the actual new URL
console.log(user.avatar_url); // should be new URL but isn't

Solution

  • It's not related to Recoil but to React, the updated value is available on the next render as setState (which Recoil is built on) is async.

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

    You should use useEffect to simulate this behavior:

    const [user, setUser] = useRecoilState(userState);
    
    setUser({ avatar_url: imageURL, ...appUser});
    
    useEffect(() => {
      console.log(user.avatar_url);
    }, [user]);