Mayank Jaiswal
Mayank Jaiswal

Reputation: 13

Why is this setState function working abnormally

I added a timer variable in state to change every second by 1 Why is it is rendering with 2,4,6,.. every second rather than 1,2,3,.. and how to imporove it ?

import React, { Component } from 'react'

export class UseRefTimer extends Component {

interval

constructor(props) {
    super(props)

    this.state = {
         timer:0
    }
}

componentDidMount(){
     this.interval = setInterval(()=>{
         this.setState( prev => (this.state.timer = prev.timer + 1))
     },1000)
}


componentWillUnmount(){
    clearInterval(this.interval)
}

render() {
    return (
        <div>
            Time : {this.state.timer} 
        </div>
    )
}

}

export default UseRefTimer

Upvotes: 0

Views: 53

Answers (1)

trixn
trixn

Reputation: 16354

You are mutating this.state.timer. You should just return the next state instead:

this.setState( prev => ({timer: prev.timer + 1}));

The reason you see the state being incremented by 2 is strict mode. In strict mode setState gets called twice to detect unintended side effects. Updater functions should be pure (side-effect-free):

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer

Upvotes: 2

Related Questions