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 (
// ...
);
};