Side effects in useMemo
See original GitHub issueFirst I just want to say great work with this!
I was reading through the code and noticed that you’re calling world.createRigidBody inside useMemo which breaks some React rules since world.createRigidBody has side effects. useMemo isn’t the best choice for this anyway because React can decide to throw away the value at any time and recompute it.
In my own integration I ended up using a getter which as far as I can tell should be React 18+ safe. The approach is described in the bottom of https://github.com/reactwg/react-18/discussions/18
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:9 (9 by maintainers)
Top Results From Across the Web
Is okay to useMemo instead of useEffect for calling side-effect ...
You should not cause any side effect in useMemo . For more on this you can read here: https://reactjs.org/docs/hooks-reference.html#usememo.
Read more >What's the big problem with (careful) side effects in useMemo?
The useMemo body does have side effects (it runs a "pause" which will be eventually followed by a "resume" when the render has...
Read more >React.useMemo and when you should use it - everyday.codes
The only difference is that useEffect is intended for side-effects (hence the name), while functions in useMemo are supposed to be pure and ......
Read more >дэн on Twitter: "@cakemakerjake useMemo() is not for side ...
useMemo () is not for side effects. It's for pure computation. Resetting state based on other state is here: reactjs.org. Hooks FAQ –...
Read more >When Using useMemo is A Really Bad Idea | by Lina Suodyte
We should also not use useMemo when the function returns a primitive value, such as a boolean or a string. Because primitive values...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Sure, feel free to take anything that is useful 😄
I think I had to create both the rigidbody and collider in a useLayoutEffect to avoid “layout shift” (not sure what it’s called in a 3d context), was some time ago so don’t remember exactly why I had to do it that way
I’m still not convinced
useMemois the right choice here, since React can throw away the value at any time. A lazy state setter might be better (useState(() => createSomeApi(refGetter))), but technically it might still violate the React rules since you’re setting/getting the ref value in render (React 18 compatibility is hard 😅)