My intention is to use a function (received by a parent component, created with useCallback
) as dependency in useEffect
and only trigger that effect if the function changes.
Consider the following simple component:
function MyComponent(props) {
const [myState, setMyState] = useState(0);
useEffect(() => {
setMyState(props.calculate(1));
}, [props.calculate])
return <h1>{myState}</h1>;
}
It receives a function calculate
in props and computes myState
from it. However I get the linting error:
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array.
I don't understand why props.calculate
is not sufficient as a dependency and we need props
. I don't want to use props
because then the effect would retrigger on every render, even if calculate
did not change. (Assume calculate
has been created using useCallback
in parent).
The following version does not get any linting errors:
function MyComponentVersion2(props) {
const { calculate } = props;
const [myState, setMyState] = useState(0);
useEffect(() => {
setMyState(calculate(1));
}, [calculate])
return <h1>{myState}</h1>;
}
My questions are:
- Why is the linter not fine with
MyComponent
?
- Are there semantical differences in
MyComponent
compared to MyComponentVersion2
?
I made a minimal example here in this codesandbox
Thank you!
question from:
https://stackoverflow.com/questions/65900551/use-functions-as-useeffect-dependencies-dependency-props-missing 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…