Kind of lost on how to optimize this piece of code

Sandbox: https://codesandbox.io/s/friendly-bell-eclcq6 I'm creating a website for a game which contains certain tools. In this case it's rendering items specific to a certain class. There's generic items (ArrayTwo.jsx) and class specific ones (ArrayOne.jsx). The class is selected outside of this component, this is handled by context which is why I just hardcoded it in the example:
const selectedClass = "ClassOne";
const selectedClass = "ClassOne";
Both arrays combined is about 80-100 items (generic + class specific items). I used the useSearchDebounce to not slow the app down while typing in the searchbox, as it would jump all over the place. I haven't done much of this stuff in React yet so I'm a bit of a noob to it. It's actually the first search box I've made (which works..) and I got a bit lost in the useMemo / useEffects. I feel the array merge + sort after that is inefficient:
useMemo(() => {
setNewArray([...ArrayOne[selectedClass], ...ArrayTwo]);
setNewArray((prev) =>
prev.sort((a, b) => {
if (a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
} else if (a.name.toLowerCase() > b.name.toLowerCase()) {
return 1;
}
return 0;
})
);
}, [selectedClass]);
useMemo(() => {
setNewArray([...ArrayOne[selectedClass], ...ArrayTwo]);
setNewArray((prev) =>
prev.sort((a, b) => {
if (a.name.toLowerCase() < b.name.toLowerCase()) {
return -1;
} else if (a.name.toLowerCase() > b.name.toLowerCase()) {
return 1;
}
return 0;
})
);
}, [selectedClass]);
I'd like to make this better on the performance side. But having only worked on React at home, I've not been able to get any feedback on this matter.
CodeSandbox
friendly-bell-eclcq6 - CodeSandbox
friendly-bell-eclcq6 using loader-utils, react, react-dom, react-scripts
2 Replies
Daryl
Daryl•14mo ago
Hey! 👋 I think you need to take a look to this: https://react.dev/learn/you-might-not-need-an-effect The React docs has been updated, and the tips they share are really useful. Now, to give more insides on what can be improved (cleaning and optimization), I forked you CodeSandbox: https://codesandbox.io/s/ecstatic-shadow-5drhfb?file=/src/App.js Things to take from it: * Remove useState when possible. As you will see in the docs, it's not completely necessary to use this hook in order to define your variables or store data. * useMemo should return a value, so if you need to use side effects, you can use useEffect. * If you want to set a state, avoid as much as possible doing it in your useEffect's.
aevitas
aevitas•14mo ago
Interesting. Thanks, I'm still a noob it seems 😄 I'll go through my project and apply change where necessary!