2

I'm considering using useMemo in this hook, but I'm not sure if would even provide any benefits.

In the example below, should I return the value with useMemo?

const useBooleanState: IUseBooleanState = (defaultValue) => {
  const [value, setValue] = useState(defaultValue ?? false);

  const setTrue = useCallback(() => {
    setValue(true);
  }, [setValue]);

  const setFalse = useCallback(() => {
    setValue(false);
  }, [setValue]);

  const toggle = useCallback(() => {
    setValue((prev) => {
      return !prev;
    });
  }, [setValue]);

  return { value, setTrue, setFalse, toggle, setValue };
};

This is the useMemo option that I'm uncertain would be beneficial:

 return useMemo(() => {
    return { value, setTrue, setFalse, toggle, setValue };
  }, [value, setTrue, setFalse, toggle, setValue]);

I've used useMemo in many React components to improve performance, but I still struggle with some cases where it's difficult to determine if it's actually helping or not.

Danilo Cunha
  • 1,048
  • 2
  • 13
  • 22
  • 1
    Well, setValue is guaranteed to be static, as are setTrue, setFalse, and toggle. The only difference is that in the first case, you will be returning a different object every time the function is called (though the values in the object will be the same) whereas in the useMemo version (I believe) the object itself will be static. If you are using the object for dependency checking, you might reduce re-runs of functions by using the usememo. – BobtheMagicMoose Apr 22 '23 at 07:19
  • 1
    The result of your hook is likely going to be destructured anyway, not passed around as a whole, so there's no reason to `useMemo` on the returned object – Bergi Apr 22 '23 at 12:20

0 Answers0