Answers for "react usestate with previous state"

2

prevstate in usestate

const [prevState, setState] = React.useState([]);

setState(prevState => [...prevState, 'somedata'] );
Posted by: Guest on June-09-2020
0

useeffect previous state

const Component = (props) => {
    const {receiveAmount, sendAmount } = props

// declare usePrevious hook
    const usePrevious = (value) => {
      const ref = useRef();
      useEffect(() => {
        ref.current = value;
      });
      return ref.current;
    }    
    
// call usePrevious hook on component state variables to store previousState
    const prevAmount = usePrevious({receiveAmount, sendAmount});
  
  	// useEffect hook to detect change of state variables
    useEffect(() => {
        if(prevAmount.receiveAmount !== receiveAmount) {

         // process here
        }
        if(prevAmount.sendAmount !== sendAmount) {

         // process here
        }
    }, [receiveAmount, sendAmount])
}
Posted by: Guest on March-15-2021
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
0

usestate access previous state

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

// on a buttton for example
<button
  onClick={selectedObj => handleObjSelection(
              prevSelected => [...prevSelected, selectedObj],
  		  ))}
>
Posted by: Guest on February-19-2021

Code answers related to "react usestate with previous state"

Code answers related to "Javascript"

Browse Popular Code Answers by Language