Skip to content

Commit 232c257

Browse files
committed
Jitter generator that should be moved to an advanced hooks article
1 parent 135a4ec commit 232c257

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

lib/components_guide_web/templates/react_typescript/reducer-patterns.html.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,22 @@ const [openMenu, tap] = useReducer(
7878
);
7979
```
8080

81+
## Jitter Generator
82+
83+
Inspired by [AWS: Exponential Backoff And Jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
84+
85+
```js
86+
const baseMs = 5;
87+
const capMs = 2000;
88+
const [{attempt, delayMs}, dispatch] = useReducer((state, random) => {
89+
return {
90+
attempt: state.attempt + 1,
91+
delayMs: random * Math.min(capMs, baseMs * Math.pow(2, attempt))
92+
};
93+
}, { attempt: 0, delay: baseMs });
94+
const nextAttempt = useCallback(() => dispatch(Math.random()), [dispatch]);
95+
```
96+
8197
## Logical Clock
8298

8399
```js

0 commit comments

Comments
 (0)