Skip to content

Commit 316a4f1

Browse files
Fix ref callback explanation in deps exercise (#252)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
1 parent 0fc5f0d commit 316a4f1

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

β€Žexercises/04.dom/02.problem.deps/README.mdxβ€Ž

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ like the speed and glare to look different. So Kellie πŸ§β€β™‚οΈ added a form
77
allow them to control those values. This is working great, but something we
88
noticed is the tilt effect is getting reset whenever you click the count button!
99

10-
πŸ¦‰ The reason this happens is because the ref callback is called every time the
11-
component is rendered (and the cleanup runs between renders). So we're
12-
re-initializing the tilt effect on every render.
10+
πŸ¦‰ The reason this happens is because we're passing an inline callback to `ref`.
11+
Callback refs run when the DOM node is added/removed, and React will also call
12+
them again if you pass a different ref callback. Because `(tiltNode) => { ... }`
13+
is a new function on every render, React runs the previous ref cleanup and then
14+
re-initializes the tilt effect on every render.
1315

1416
πŸ‘¨β€πŸ’Ό This is inefficient and it's a jarring experience if the user clicks on the
1517
corner of the count button. We want the effect to only re-initialize when the
@@ -37,7 +39,8 @@ We do this using the dependency array which is the second argument to
3739
cleanup function and then invoke the effect callback again.
3840

3941
By default, if you don't provide a second argument, `useEffect` runs after every
40-
render (similar to what we're currently experiencing with the `ref` callback).
42+
render (similar to what we're currently experiencing with the inline `ref`
43+
callback, because it's a new function on every render).
4144
While this is probably the right default for correctness, it's far from optimal
4245
in most `useEffect` cases. If you're not careful, it's easy to end up with
4346
infinite loops (imagine if you're calling `setState` in the effect which

0 commit comments

Comments
Β (0)