SKK
SKK

Reputation: 184

Callback in props of React component - correct way to fire

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

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You mention

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

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

Related Questions