I have a function which essentially acts as a .map to create JSX elements out of a list. I wanted to verify that my chain of logic for the memoization is correct, and that I have understood the dependencies.
const createJSXButtons = useCallback((buttonList) => {
const jsxList = [];
for (let button of buttonList) {
jsxList.push(<button isToggled={parentState}>{button}</button>);
}
return jsxList;
}, [parentState]);
This way, when I execute something like:
const myButtons = createJSXButtons(['R', 'U', 'F']);
I would get 3 JSX buttons inside myButtons.
As you can see, createJSXButtons captures a parent state within a closure, and is added as a dependency to the useCallback to prevent stale data.
However, I would also like to memoize the creation of myButtons, how can I do this? My first instinct was to use useMemo, but I was hoping someone could verify my approach.
const myButtons = useMemo(() => {
createJSXButtons(['R', 'U', 'F'])
}, [createJSXButtons]);
The idea is whenever createJSXButtons changes, which only happens when parentState changes, then and only then myButtons will change. And we need myButtons to change when the parentState changes to ensure that each button is correctly receiving the correct isToggled boolean.
Have I understood the above flow of logic correctly? Kindly note I'm not asking how to use useMemo, but rather if my chain of logic is correct, specific to this use case.