'What's difference between this.props and props from setState() updater function?

What is the difference between these?

this.setState((state) => ({counter: state.counter + this.props.step}))

and

this.setState((state, props) => ({counter: state.counter + props.step}))

I always thought there is no difference because setState() doesn't update props, it updates only state. Maybe I don't get something.



Solution 1:[1]

According to React Docs

this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

What that means ?

let's imagine your props.step here is 1, and in the same time you execute the counter increment , another setState increment the step by 1, you will still get 1 here like this

   function Parent(){
  const [step, setStep] = useState(1)
   return <>
         <button onClick={() => setStep(2)}>icrement step</button>
         <Child step={step} />
     </>
}

you will still get 1 here

this.setState((state) => ({counter: state.counter + this.props.step})) // props.step will remain 1

thats why you should pass props in your setState

this.setState((state, props) => ({counter: state.counter + props.step}))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1