0

I have a similar warning to this one, however I don't want the value it wants me to add in the dependency array, so should I suppress the warning?

I have an array and an index which are both stored as state in a component. I want to have a useMemo hook to update a value every time the index changes, based off the value in the array that the index is pointing to. I don't want it update when the array changes, so I only have the index in the array of dependencies. Is there a way to get around this without suppressing the warning?

Jeffmagma
  • 452
  • 2
  • 8
  • 20

1 Answers1

0

There's a few ways you can do this, without seeing your code it's hard to say which will work best for you. Assuming your component looks something like this:

const MyComponent = () => {
  const [values, setValues] = useState<number[]>([0]);
  const [index, setIndex] = useState(0);

  // Calculate the value as 10x whatever the number is at index:
  // WARNING - missing dependency
  const calculatedValue = useMemo(
    () => 10 * values[index],
    [index]);

  return (
    // ...
  );

You could use a ref to keep track of the values, and then use that in your callback:

const valuesRef = useRef<number[]>(values);
valuesRef.current = values;

const calculatedValue = useMemo(
  () => 10 * valuesRef.current[index],
  [index]);

But a better solution, if you only want to change the calculated value when the index changes, is handle the calculation in the callback:

const runCalculation = (value: number) => 10 * value;

const MyComponnet = () => {
  const [values, setValues] = useState<number[]>([0]);
  const [index, setIndex] = useState(0);
  const [calculatedValue, setCalculatedValue] = useState<number>(
    () => runCalculation(values[index])
  );

  const handleChangeIndex = (nextIndex: number) => {
    setIndex(nextIndex);
    setCalculatedValue(runCalculation(values[nextIndex]));
  };

  return (
    // ...
  );
};
gerrod
  • 6,119
  • 6
  • 33
  • 45