Skip to content

Commit 8bff007

Browse files
committed
Clarify why the debouncing solution uses a ref
1 parent 0821e7d commit 8bff007

1 file changed

Lines changed: 2 additions & 0 deletions

File tree

‎src/content/learn/referencing-values-with-refs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,8 @@ button { display: block; margin: 10px; }
527527

528528
A variable like `timeoutID` is shared between all components. This is why clicking on the second button resets the first button's pending timeout. To fix this, you can keep timeout in a ref. Each button will get its own ref, so they won't conflict with each other. Notice how clicking two buttons fast will show both messages.
529529

530+
Moving `let timeoutID` inside `DebouncedButton` would also keep the buttons independent in this example, because they don't re-render. However, if a button re-rendered (for example, because its parent re-rendered), the component would create a new local variable, so the next click couldn't clear the previous timeout. Using `useRef` preserves the timeout ID between renders.
531+
530532
<Sandpack>
531533

532534
```js

0 commit comments

Comments
 (0)