@@ -7,9 +7,11 @@ like the speed and glare to look different. So Kellie π§ββοΈ added a form
77allow them to control those values. This is working great, but something we
88noticed 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
1517corner 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
3739cleanup function and then invoke the effect callback again.
3840
3941By 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).
4144While this is probably the right default for correctness, it's far from optimal
4245in most ` useEffect ` cases. If you're not careful, it's easy to end up with
4346infinite loops (imagine if you're calling ` setState ` in the effect which
0 commit comments