Reputation: 184
Suppose I have a component which is like
function Child(props: { onSelect: () => void }) {
...
useEffect(() => {
// want to fire onSelect here
}, [...]);
...
}
Since props.onSelect might change every render (e.g. arrow function), I can't add it to the dependency list of useEffect and call it directly. I used a reducer instead:
const [, dispatch] = useReducer((state: undefined, action: T) => {
props.onSelect(action);
return undefined;
}, undefined);
useEffect(() => {
dispatch(...);
}, [...]);
But now I get the error "Warning: Cannot update a component (Parent
) while rendering a different component (Child
)."
What's the correct way to fire the parent's onSelect inside some useEffect?
Upvotes: 1
Views: 133
Reputation: 195992
You mention
Since
props.onSelect
might change every render (e.g. arrow function), I can't add it to the dependency list ofuseEffect
and call it directly
You can, but you should make sure that it does not change if there is no reason.
You should use a useCallback for it on the parent component, so that it remains the same.
function Parent (){
...
const onSelect = useCallback(() => {
// set local state here
}, []);
...
return ... <Child onSelect={onSelect} />
}
Upvotes: 1