G
G
Gary_Ihar2021-07-01 10:13:41
React
Gary_Ihar, 2021-07-01 10:13:41

Tell me in simple terms please. What's going on here?

Can you please tell me what is happening under the hood of React? I just want to understand, and not just stupidly know the solution to the problem. Googled, but everything around and around

Option 1

const [counter, setCounter] = useState(0)

    const clicker = () => {
        setCounter(counter + 1)
        setCounter(counter + 1)
        setCounter(counter + 1)
        setCounter(counter + 1)
    }
    console.log('render')
    return ( 
        <div>
            <div>{counter}</div>
            <button onClick={clicker}>counter</button>
        </div>
    )

Option 2

const [counter, setCounter] = useState(0)

    const clicker = () => {
        setCounter(prev => prev + 1)
        setCounter(prev => prev + 1)
        setCounter(prev => prev + 1)
        setCounter(prev => prev + 1)
    }
    console.log('render')
    return ( 
        <div>
            <div>{counter}</div>
            <button onClick={clicker}>counter</button>
        </div>
    );


Here's what I think:
If there are several setCounter(counter + 1) in a row, then React just takes the last one and does it. Even if you pass the setCounter(() => counter + 1) function and call it in succession, the last one will still be executed. But as soon as we start using the setCounter((preState) => preState + 1) argument of this function , then somewhere under the hood, the react starts doing everything sequentially and remembers all actions with this state.

I could be wrong somewhere, so please correct me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2021-07-01
@mmmaaak

Learn what closures are in javascript

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question