user18209107
user18209107

Reputation:

Maximum update depth exceeded. When invoke parent function in child component

I want to call parent component function, when child component mount but I get this error:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

My code is:

function Light(props: IProps) {
    let { language } = useContext(LangContext);
    let { noResponse, off, onn } = language == Languages.fa ? fa_Pages.node : en_Pages.node;

    let { node: { status, nodeName, icon, roomName, name, serial } } = props;
    let { backgroundColor, callback, clientId } = props;

    useEffect(() => {
        if (!status) {
            let message = `MSG:DAT:${nodeName}-STATUS:STA*END*`;
            let topic = `IHS/${clientId}/${serial}`;

            console.log("callback ", topic, message);
            callback({ topic, message })
        }
    }, [status])
}

How can I fix this error?

Upvotes: 0

Views: 191

Answers (1)

Jonathan Wieben
Jonathan Wieben

Reputation: 671

In your useEffect, you have a dependency on status. This means that the effect will run every time the status changes.

If your effect callback changes the status value, you might run into an infinite loop (status changes => callback updates status => status changes => ...)

Upvotes: 1

Related Questions