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 :: Slice and Splice -Javascript 2 
Javascript :: how to put multiple conditions in if statement node .js 
Javascript :: what is so called abstractions in javascript 
Javascript :: graphql nested schema 
Javascript :: what are array methods in javascript 
Javascript :: change text color according to background js 
Javascript :: javascript math round 
Javascript :: javascript trunc 
Javascript :: are you sure alert js 
Javascript :: how to add google map in react js 
Javascript :: extract data from pdf nodejs 
Javascript :: push pop in javascript 
Javascript :: vue sidebar 
Javascript :: random number between 1 and 10 javascript 
Javascript :: vanilla js 
Javascript :: how to loop over dom objects javascript 
Javascript :: name function in javascript 
Javascript :: how to read excel file in nodejs 
Javascript :: save or update mongoose 
Javascript :: react native fast image webp ios 
Javascript :: scrollbar position 
Javascript :: add 7 days in date using jquery 
Javascript :: default function parameters javascript 
Javascript :: javascript array looping 
Javascript :: Material-ui add circle icon 
Javascript :: && in javascript 
Javascript :: datapack structure 
Javascript :: dark mode javascript 
Javascript :: Get home directory in nodejs windows 
Javascript :: javascript console log current directory 
ADD CONTENT
Topic
Content
Source link
Name
8+5 =