Patrickkx
Patrickkx

Reputation: 1870

What to put in the dependency array in React.useMemo

Consider situation:

const App = ({ data = [], users = [] }) => {
  const selectedId = React.memo(() => {
    return data.find((id) => id === 'someId');
  }, [data]);

  const userIds = React.memo(() => {
    return users.map(({ id }) => id);
  }, [users]);

  const finalIds = React.memo(() => {
    return userIds.find((id) => id === selectedId);
  }, []);

  return finalIds.toString();
}

What should I put in the dependency array in finalIds?

Should I:

Upvotes: 0

Views: 1403

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85012

You put any variables that you use inside the calculation. In other words, [selectedId, userIds]. When those variables change, you need to repeat the calculation, or finalIds will be stale.

If you use eslint, i'd recommend using eslint-plugin-react-hooks. It can spot if you're missing a variable from the dependency array and fill them in automatically.

Upvotes: 1

Related Questions