How Recoil Updates Only Subscribed Components
To use
Recoil
, you first need to wrap your app with RecoilRoot
. While it uses Context API
internally to pass down state, it doesn't trigger full re-renders like regular React Context APIThis is because the store being passed down isn't a regular
React
state
, so changes to this context
don't cause re-renders of components it passes through
So how do components using a
Recoil
atom
re-render when that atom
's value
changes through setState
?Looking at
useRecoilValue
, we can see it uses useStoreRef
to get a reference to the Recoil
store and uses the useRecoilValueLoadable
hook to get a Loadable
It then uses
useState
to create a setState
function named forceUpdate
, which is set as a callback function for subscribeToRecoilValue
Components using
useRecoilValue
subscribe to changes in their recoilValue
through the subscribeToRecoilValue
function. When the Recoil
runtime triggers the registered callback, the component's useState
updates, causing only that specific component to re-renderData is declared in atom units, and state management becomes simpler using useRecoilState, which works very similarly to React's useState hook