Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

When I want to memoize something slightly complex, for simplicity's sake let's say sorting an array of objects based on one of it's keys. I can put that in a useMemo and it won't sort it again when the page eventually rerenders for some reason.

Usually that array is mapped elsewhere and those child components might also re render if the array is recalculated.

useEffects are when I need to call something outside of react, or when the page gets mounted or I need to call a function when something changes.

I'm still fairly new to this, the above examples may scream bad architecture to those more experienced, all criticisms welcome :)



> all criticisms welcome :)

No criticism really. Your useMemo example is the right use. Your useEffect use is fine, but for things like api calls (which 'call something outside of react' may refer to), you're often better leaning on something like react-query, which is of course built on top of useEffect. So still the right tool, but let others handle many of the sharp edges around that problem.


Thanks. I've started with rtk and saga hence the useEffect. I've since moved to rtk query.


> I can put that in a useMemo and it won't sort it again when the page eventually rerenders for some reason

useMemo dependency smell. This is almost always because your dependencies are wrong. This can often happen if you put a dependency as [object] instead of [object.field] due to how JavaScript maps objects to memory.


Never thought of it that way. What if it's an array though, how will I put it as a dependency?


useMemo is quite nice when you're doing data transformation against some API call or other big data structure.


Yes, it is, but you still have to declare your dependencies correctly.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: