Home > Back-end >  How the arrow function is preventing re-rendering in the code
How the arrow function is preventing re-rendering in the code

Time:10-22

The following code holds the query,

import React,  {useEffect , useState} from 'react'
import './Body.css'
export default function Navbar() {
    const  [value , setvalue] = useState(0);
    useEffect(() => {
      console.log("useEffect ran");
    }, [])
    
    return (
        <>
            <div>
                <button onClick={ () => setvalue(value-1)}> - </button>
                <button> {value}</button>
                <button onClickCapture={() => setvalue(value 1)} >   </button>
            </div>
        </>
    )

When I am using onClick= {setvalue(value 1)} then I am getting an error for too many renderings.

But, when I am using an arrow function then it is preventing the renders.

Can you tell me how is it happening?

CodePudding user response:

When you use

<button onClick={setvalue(value-1)}>

You are adding as the handler of onClick the result of the call function setvalue(value-1).

It is equivalent to calling setvalue(value-1) in the body of the component and using its return value in the onClick, like this:

export default function Navbar() {
    // ...
    const resultOfCall = setvalue(value-1);
    
    return (
        <>
            <div>
                <button onClick={resultOfCall}> - </button>

And this errors because setvalue(value-1) changes the value state, which is in your JSX in <button> {value}</button> (so it changes every time the render/component function is called).

The fix

When you do instead:

<button onClick={() => setvalue(value-1)}>

You are adding as the handler of the onClick a function that, when executed, calls setvalue(). And such function will be executed when the user clicks the button.

CodePudding user response:

Suppose there is a function which adds to numbers

function addNumbers(a, b) {
    return a   b
}

to see the result you need to use

console.log(addNumbers(3,4))
// or
alert(addNumbers(3,4))

now, how these things work? the addNumbers(3,4) returns the result, and then it console logged in the browser console console.log(7). so the console.log()runs the result of addNumber(3,4), this line is very important to keep in mind.

now, what your code onClick={setvalue(value 1)} is doing, is onClick={1}, your code runs before onClick event runs it, resulting too many error renderings. now if you use an arrow function onClick={() => setvalue(value 1)}, it basically is a wrapper just like console.log(addNumbers(3,4)), setvalue(value 1) sets the state, and then on click it returns the value. I hope you got your answer.

  • Related