📎 Webclip
How SWR works behind the scenes
The article rebuilds a simplified version of SWR from a custom async hook. It first moves fetched data out of component state and into a module-level cache keyed by string, then adds mutate and reload behavior on top of that cache.
It then shows why that still is not enough on its own. Because cache changes do not trigger React renders automatically, the hook needs a force-update mechanism and then a subscribe/unsubscribe layer so multiple components using the same key can react to the same cached value.
Reading notes#
- The post starts from a custom
useAsyncFunctionhook that can fetch any promise-returning function, not justfetch. - Data is moved from
React.useStateto a module-scopeMap, and the hook receives akeyso different consumers do not overwrite each other. - The hook returns only
erroras state, whiledatais read from the cache with the given key. - A
mutatefunction is added to update cached data and exposed in the hook return value. - A
loadfunction is extracted from the effect so it can also be returned asreload. - The first cache-based version does not re-render after promise resolution because it no longer uses
useStatefor data. - A
useForceUpdatehook is introduced to force a component re-render after cache mutation. - That still leaves other components unsynchronized, because only the component that loads or mutates data re-renders.
- The cache is then split into a separate module with
getCache,setCache,subscribe, andunsubscribe. setCachenotifies subscribers for a key, and the hook subscribes on mount and unsubscribes on unmount or key change.- The final version exposes
data,error,mutate, andreload, but the post says it is still only a basic approximation of SWR and not production code. - The article lists features included and not included, such as returning cached values while fetching, deduping requests, focus revalidation, interval refetching, pagination, dependent fetching, and Suspense.
- The conclusion says SWR or react-query is preferable for remote data, while custom hooks with
useStateanduseReducerare kept for application state.
