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

usestate access previous state

const [arrayOfObjs, handleObjSelection] = useState([]);

// on a buttton for example
<button
  onClick={selectedObj => handleObjSelection(
              prevSelected => [...prevSelected, selectedObj],
  		  ))}
>
Comment

PREVIOUS NEXT
Code Example
Javascript :: en eternal gloden braid 
Javascript :: hammerjs 
Javascript :: gravity form on submit jquery 
Javascript :: homepage field in package.json 
Javascript :: use localstorage react hook 
Javascript :: notify jquery 
Javascript :: jquery deferred 
Javascript :: svg clientx 
Javascript :: how to make data toggle=modal always active 
Javascript :: add to array applescript 
Javascript :: try catch 
Javascript :: how to take input n number in js 
Javascript :: flex slider 
Javascript :: react fetch data in for loop 
Javascript :: github create react app buildpack 
Javascript :: react native ant design 
Javascript :: socket io new server multiple origins 
Javascript :: function create array javascript 
Javascript :: count items in json 
Javascript :: javascript rest 
Javascript :: JavaScript Object Accessors 
Javascript :: ternary operator nodejs 
Javascript :: decode jwt token nodejs 
Javascript :: push array into array javascript 
Javascript :: cheapest node js hosting 
Javascript :: upload bloob javascript 
Javascript :: angular material moduel 
Javascript :: js for i in html collection 
Javascript :: passing json as datasource to jasper report library 
Javascript :: concat no and string in javascript 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =