Post

This isn’t in the effect, it’s in the promise callback, so it’s fine but still has footguns because of race conditions. Better to use use().

There are 3 use cases for fetch: - get data (GET) - refresh data (GET) - change data (POST, PUT, DELETE)

Starting in 19, you shouldn’t need to fetch in an effect for any of these use cases. Initial GET should be cached and read in render with use(). Refresh GET should clear the promise cache to trigger with use() again. POST/PUT/DELETE mutations should be done in event handlers with actions.

5 reposts41 likes

Cool, very curious how to implement revalidation after mutation. Is it documented? I have not found anything about that (but maybe I’m blind 😅)

I’m working on the docs, but if you’re not using a library the easiest way is to just set the promise in state function refresh() { startTransition(() => { setState(fetch(…)) }) }

const cache = new Map(); function Component() { const [promise, setPromise] = useState(() => { if (!cache.has(url)) { cache.set(url, fetch(url).then(r => r.json())) } return cache.get(url); }); const data = use(promise); // render data ... }

I didn't know about the clearing promise cache option. Good to know it! It definitely drops most of the needs to setState in an asynchronous manner just because of a fetch call