0

I'm trying to trace excess rerenders in a child component. I'm using a useEffect hook to track changes in the props and changes in state. Like this:

export default function Child(props) {
  const [user] = useAuthState(firebase.auth());
  const [error, setError] = useState(false);

  useEffect(() => console.log(user, error, props), [user, error, props]);
  console.log('render');

  return (<p>Test</p>);
};

What this logs is:

render
{userObject: value}, false, {prop1: value1}
render

I couldn't figure out why render was logged twice if my state and props were only changing once. In this answer, it said that rerenders of parent components trigger rerenders of child components, as well as changes in props and changes in child state. I checked that the parent component renders twice (it fetches data for the child). But I only render the child component on the second render of the parent (when the data is ready).

export default function Parent {
   const [data, setData] = useState(null);
   useEffect(() => getData({callback: setData}), []); //Get data on first render. 

   console.log(data); //Output is null, then {prop1: value1}

   let returnItem;
   if (data) {
     returnItem = <Child data={data} />
   } else returnItem = null;

   return ({returnItem});
}

I've checked that the return item is null on the first render. And also I've checked that the parent component only renders twice. So I'm pretty sure that the Child should only be rendered on the second time. Does anyone know what else could be leading the Child to log render twice?

Madhav Malhotra
  • 385
  • 1
  • 5
  • 17

1 Answers1

0

The console log inside useEffect will only run after the component is mounted. The console log outside the useEffect will also run as the component is being mounted. This is why you’re getting 2 prints on the ‘render’ console log and only one on the useEffect console log.

Kevin Gelpes
  • 581
  • 4
  • 6