Iam new to React this is my first Simple small project . Iam getting this error and I found the reason why it is happening. But I don't know where my code repeatedly rendering that particular component. please help me to tackle this issue.
function Button(props)
{
return(<button onClick={props.count(props.value)}>{props.value}</button>);
}
function Display(props)
{
return(<div>{props.messege}</div>);
}
function App()
{
const[counter,setCounter]=useState(0);
const countfunction=(val)=> setCounter(counter+val);
return(
<div>
<Button count={countfunction} value={10} />
<Button count={countfunction} value={5} />
<Button count={countfunction} value={1} />
<Button count={countfunction} value={120} />
<Display messege={counter}/>
</div>
);
}
ReactDOM.render(<App/>,document.getElementById('mountNode'));```
This is my error state
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.
at checkForNestedUpdates
at scheduleUpdateOnFiber
at dispatchAction
at Object.countfunction [as count]
at Button
at renderWithHooks
at updateFunctionComponent
at beginWork
at beginWork$1
at performUnitOfWork
This is the offending line
return(<button onClick={props.count(props.value)}>{props.value}</button>);
This is because the function is being called on render, instead of when it is clicked, to get it to only run on click you need to wrap it in an anonymous function, like so...
return(<button onClick={() => props.count(props.value)}>{props.value}</button>);