< Back to Coding

Setting State in a setTimeout method

If you do:

      this.setState({something: "changed"}); 
    }, 1000);

You’ll get an error saying “this.setState is not a function”. To fix it for a class function, put it in a function (in this case handleClick() ), bind it in the constructor and use an arrow function in the setTimeOut:

constructor(props) {
    this.state = {
      something: false
    this.handleClick = this.handleClick.bind(this);

//put in function
    this.setState(prevState => ({
      con1: !prevState.somthing

//use arrow function
setTimeout(() => {this.handleClick()}, 1000);

For a function component, also use an arrow function but you’ll also need to use useRef to get the most current value of the state in case it changes before setTimeout is called:

const [something, handleClick] = useState(false);

  const somethingRef = useRef(something);
  somethingRef.current = something;

setTimeout(() => {handleClick(!somethingRef.current)}, 1000);

Leave a Reply

Your email address will not be published. Required fields are marked *