Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

usestate previous state

const Foo = (props) => {
  const [name, updateName] = useState('Doe');

  return (
    <div>
      <div>{name}</div>
      <button
        onClick={() => updateName((prevState) => (
          `Old value was ${prevState}`
    	  )
        )}
      >
        Click me
      </button>
    </div>
    )
}


export default Foo;
Comment

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);
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to play sound on load js 
Javascript :: javascript two decimal places after division 
Javascript :: javascript fibonacci sequence recursion 
Javascript :: stream recording javascript 
Javascript :: js bubble sort 
Javascript :: how to get the size of the window in javascript 
Javascript :: ajax select2 
Javascript :: confirm before close modal 
Javascript :: angular list contains property 
Javascript :: prisma query log 
Javascript :: css class list 
Javascript :: npm got 
Javascript :: set attribute javascript 
Javascript :: response.json() promise pending 
Javascript :: for in loop key 
Javascript :: deploy vue js to shared hosting 
Javascript :: js create array with default value 
Javascript :: js char array to string 
Javascript :: nodemailer, mailer, nodemailer npm 
Javascript :: node js event emitter 
Javascript :: using async function in useeffect 
Javascript :: for of loop in es6 
Javascript :: node js response header 
Javascript :: webpack error cannot find module 
Javascript :: how to convert jsonobject to string in java 
Javascript :: text.toUpperCase is not a function 
Javascript :: node js and react js difference 
Javascript :: vuetify autocomplete get input value 
Javascript :: javascript copy div element content 
Javascript :: discord js lockdown command 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =