Consider the following React component:
interface Props {
cpi: number;
onCpiChange: (value?: number) => void;
}
const Assumption: FunctionComponent<Props> = (props: Props) => {
const [cpiValue, setCpiValue] = useState<number>();
useEffect(() => {
if (props.cpi != cpiValue) {
setCpiValue(props.cpi);
}
}, [props.cpi]);
return (
<FormattedNumberInput
value={cpiValue}
onBlur={() => props.onCpiChange(cpiValue)}
onValueChange={setCpiValue}
/>
);
};
export default Assumption;
The useEffect is complaining that it's missing the cpiValue - and as it's not in the dependency array it doesn't update when comparing using props.cpi != cpiValue. I don't want this useEffect to trigger every time the cpiValue changes. How would I have this useEffect respond only to when props.cpi changes yet still have access to the other variables required such as cpiValue with which I'm comparing against?
Additionally when initially learning React Hooks I learned that there are ways of controlling when a useEffect will trigger as follows:
- If you don't include a dependency array it will update on every render.
- If you provide an empty array it should update only on the first time the component loads
- If you provide any members inside the array the
useEffectwill trigger every time that one of these variables were to update.
The only one of these that makes sense is the third option. Options one and two have no scope to variables outside of the useEffect if you don't include them in the dependency array, but then adding the required variables to the dependency array changes the definition of the useEffect from 1 or 2 to 3. Am I missing something here?