skip to Main Content

Problem: UseEffect of Child widget is getting executed thrice even though i have given empty dependency array. For simplicity of code I have omitted some logic in Parent component that loads childWidget dynamically. If needed I can add that too here but is there any issue like conflicts of forwardRef and UseEffect Or something else is missing.

Code:

const ChildWidget = (props) =>{
useEffect(()=>{ console.log('ChildWidget useEffect func')},[])

return (<div>ChildWidget</div>)
}

const Parent = forwardRef((props, ref) =>{
useImperativeHandler(ref,()=>({
show(){.. //some code ..}
hide(){.. //some code ..}
}))

useEffect(()=>{console.log('Parent UseEffect')},[]);

return(
<ChildWidget a={props.a} b={props.b}/>
)
})

Result:
UseEffect of Parent is always called once but of that of child it is called thrice.

2

Answers


  1. Try this once…

    import React, { useEffect } from 'react';
    import { forwardRef, useImperativeHandler } from 'react';
    
    const ChildWidget = () => {
      useEffect(() => {
        console.log('ChildWidget useEffect func');
        // Add any code you want to run when the component mounts or updates
        // If you need to run code only when the component mounts, remove the dependency array []
      });
    
      return <div>ChildWidget</div>;
    };
    
    const Parent = forwardRef((props, ref) => {
      useImperativeHandler(ref, () => ({
        show() {
          // Some code for the show function
        },
        hide() {
          // Some code for the hide function
        },
      }));
    
      useEffect(() => {
        console.log('Parent UseEffect');
        // Add any code you want to run when the component mounts or updates
        // If you need to run code only when the component mounts, remove the dependency array []
      });
    
      return <ChildWidget a={props.a} b={props.b} />;
    });
    
    export default Parent;
    
    Login or Signup to reply.
  2. In my knowlegde, issue with the useEffect in the ChildWidget component being called multiple times is because of a syntax error. The empty dependency array [] should be passed as the second argument to useEffect, not as an argument to the function itself.

    const ChildWidget = (props) => {
      useEffect(() => {
        console.log('ChildWidget useEffect func');
      }, []);
    
      return <div>ChildWidget</div>;
    };
    
    const Parent = forwardRef((props, ref) => {
      useImperativeHandler(ref, () => ({
        show() {
          //.. //some code ..
        },
        hide() {
          //.. //some code ..
        },
      }));
    
      useEffect(() => {
        console.log('Parent UseEffect');
      }, []);
    
      return <ChildWidget a={props.a} b={props.b} />;
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search