React useMemo dependency array with extra dependency

Viewed 43

From the react docs:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Is it bad practice to add another value to the dependency array, even if it's not used in computeExpensiveValue?

Example:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b, c]);

I have a memoizedValue that needs to be recomputed when the state of c changes. My linter tells me it's an unnecessary dependency which leads me to believe there is an alternative solution that makes more sense...

The only alternative I can think of is storing memoizedValue as a state value, then wrap the setMemoizedValue in a useEffect hook that has c as a dependency.

Example:

const [stateNotMemo, setStateNotMemo] = useState({})

useEffect(() => setStateNotMemo(() => return {...someObject},[c])

Edit: Basically what I am trying to do is update the memoizedValue when I close out of a modal.

const [showModal, setShowModal] = useState(false);

const memoizedValue = useMemo(() => {
    calculateNewValueWhenModalCloses(a,b);
},[a,b,showModal])

const handleCloseModal = () => {
    setShowModal(false);
}

const handleOpenModal = () => {
    setShowModal(true);
}

// Then some jsx that has two buttons. 
// one with onClick={handleCloseModal} (passed to modal component)
// and another with onClick={handleOpenModal}

1 Answers

You can, but it's a code smell. It indicates that computeExpensiveValue is impure and that its output depends on c in some way, despite not being an argument. If feasible, refactor it to pass c as an additional argument.

useMemo(() => computeExpensiveValue(a, b, c), [a, b, c]);
Related