Answers for "this setstate previous state react"

0

this setstate previous state react

state = {count: 0}

increment = () => { 
this.setState(previousState => ({
count: previousState.count + 1
}))
}
Posted by: Guest on June-23-2020
1

when to use previous state in useState

import React, { useState } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
        Delayed Counter (basic)
      </button>
      <button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
        Delayed Counter (functional)
      </button>
      <button onClick={() => setCount(count + 1)}>Immediate Counter</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);
Posted by: Guest on October-22-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language