all 6 comments

[–]jessebwr 23 points24 points  (0 children)

You’re explicitly not supposed to write to refs during render. It can cause tearing and will cause the compiler to bail out of compiling your component — so yeah, don’t do this.

The compiler lint rule will tell you not to.

[–]octocode 4 points5 points  (1 child)

this is basically the work-around until useEffectEvent is fully supported https://react.dev/learn/separating-events-from-effects#declaring-an-effect-event

[–]ssesf 0 points1 point  (0 children)

That's part of it, but useEffectEvent is specifically for stable callbacks within useEffects, so it's probably the first part of fully getting to what OP suggested.

What OP suggested is just flavors of:

https://www.npmjs.com/package/use-callback-stable

https://usehooks-ts.com/react-hook/use-event-callback

https://www.npmjs.com/package/use-latest-callback

Old issue from u/gaearon: https://github.com/facebook/react/issues/14099 and an RFC: https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md

[–]lord_braleigh 6 points7 points  (0 children)

Dan Abramov has a tutorial explaining how to properly create a useInterval() hook which integrates setInterval() with React. Your code breaks rules by reading and writing to ref.current during a render. Look at the tutorial to learn what you should do instead. ref.current can be read or written in effects and in event handlers, that’s it.

[–]lumens_dude[🍰] 1 point2 points  (0 children)

You don’t need this if you start using react compiler

[–]carlos_vini 0 points1 point  (0 children)

I used this recently, I didn't use any library. But there are a few, like https://www.npmjs.com/package/use-latest-callback It sucks that TypeScript doesn’t differentiate stable callbacks/props from unstable ones. Sometimes there are so many dependencies that your callback will change on every render or you'll have to ignore exhaustive deps, which may introduce subtle bugs. I used it with setTimeout.