What is it?
Let's say we have a component with a default prop like this
importReact,{useEffect,useState}from"react";constRerenderChild=({value=[]})=>{const[valueFromProp,setValueFromProp]=useState([]);useEffect(()=>{setValueFromProp(value);},[value]);return(<div>{/* ...component */}</div>);};exportdefaultRerenderChild;
Whenever thevalue
prop is nullish (not set by the calling component), theuseEffect
causes the component to render infinitely. This is theDefault Props Render Trap. We get something like this in the browser console.
Why It Happens
When we don't provide the value for thevalue
prop it takes the default value provided as argument, which in our case is[]
. This triggers theuseEffect
hook which updates thevalueFromProp
state. The state change causes the component to re-render.
Now when the component re-renders, it takes the new prop values which again are the default one's. This again triggers theuseEffect
and the whole cycle repeats. That's why we end up with an infinite loop.
The Solution
We have to make the default prop values a part of our component definition. We can do that in these ways.
1. Use defaultProps property.
We can set the default props value by using the component'sdefaultProps property. Our component now becomes
importReact,{useEffect,useState}from"react";constRerenderChild=({value})=>{const[valueFromProp,setValueFromProp]=useState([]);useEffect(()=>{setValueFromProp(value);},[value]);return(<div>{/* ...component */}</div>);};RerenderChild.defaultProps={value:[],};exportdefaultRerenderChild;
2. Declare default props as constants.
We can declare constants outside of our component and set them as our default prop value.
importReact,{useEffect,useState}from"react";constDEFAULT_VALUE=[];constRerenderChild=({value=DEFAULT_VALUE})=>{const[valueFromProp,setValueFromProp]=useState([]);useEffect(()=>{setValueFromProp(value);},[value]);return(<div>{/* ...component */}</div>);};exportdefaultRerenderChild;
Hope this helps you to avoid the infinite loop. Thanks 😊.
Top comments(2)

A pretty copy of this awesome post on Stack Overflow:stackoverflow.com/q/71060000/6877799
For further actions, you may consider blocking this person and/orreporting abuse