Search code examples
reactjsstorybookreact-usememo

React useMemo not returning correct memorized value


Every time the component re renders the variable initalValues is console logging a different value, though the useMemo function is never running (The console.log(options, 'here') is never being console logged. If it did re run the value would be correct but it seems to be getting overwritten at some point randomly or retrieved from memory wrong.

Any help would be greatly appreciated.

Component code.

const initialValues = useMemo(() => {
    console.log(options, 'here');
    return options.filter(item => item.state).map(item => item.value);
}, [options]);
const initSingleValues = useMemo(() => defaultValue ? [defaultValue.value] : [], [defaultValue]);

console.log(initialValues, initSingleValues, 'init');

Code sandbox. When you toggle a checkbox, it adds it to the initialValues memorized value.

https://codesandbox.io/s/react-playground-forked-o20e5s?file=/Component.js


Solution

  • const initialValues = useMemo(() => {
      console.log("here");
      return options.filter((item) => item.state).map((item) => item.value);
    }, [options]);
    
      console.log(initialValues, "init");
    const [values, setValues] = useState(
      chooseMultiple ? [...new Set(initialValues)] : initSingleValues // NOT JUST initialValues
    );
    const [showError, setShowError] = useState(false);
    
    useEffect(() => {
      setShowError(false);
      setValues(chooseMultiple ? [...new Set(initialValues)] : initSingleValues); // NOT JUST initialValues
    }, [chooseMultiple, initialValues, initSingleValues]);
    

    As you can see from the above the code snipet, I use [...new Set(initialValues)] for setValues, not just initialValues to creat an absolutely another array.