Skip to content

Commit e476c69

Browse files
authored
Update README.md
1 parent 71c8fd1 commit e476c69

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,31 @@ const StarwarsHero = ({ id }) => {
247247
};
248248
```
249249

250+
#### How to have better control when things get fetched/refetched?
251+
252+
Sometimes you end up in situations where the function tries to fetch too often, or not often, because your dependency array changes and you don't know how to handle this.
253+
254+
In this case you'd better use a closure with no arg define in the dependency array which params should trigger a refetch:
255+
256+
Here, both `state.a` and `state.b` will trigger a refetch, despite b is not passed to the async fetch function.
257+
258+
```tsx
259+
const asyncSomething = useAsync(() => fetchSomething(state.a), [state.a,state.b]);
260+
```
261+
262+
Here, only `state.a` will trigger a refetch, despite b being passed to the async fetch function.
263+
264+
```tsx
265+
const asyncSomething = useAsync(() => fetchSomething(state.a, state.b), [state.a]);
266+
```
267+
268+
Note you can also use this to "build" a more complex payload. Using `useMemo` does not guarantee the memoized value will not be cleared, so it's better to do:
269+
270+
```tsx
271+
const asyncSomething = useAsync(() => fetchSomething(buildFetchPayload(state)), [state.a, state.b, state.whateverNeedToTriggerRefetch]);
272+
```
273+
274+
250275
#### How to support retry?
251276

252277
Use a lib that simply adds retry feature to async/promises directly. Doesn't exist? Build it.

0 commit comments

Comments
 (0)