Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react use last state

import { useState, useEffect, useRef } from "react";
// Usage
function App() {
  // State value and setter for our example
  const [count, setCount] = useState<number>(0);
  // Get the previous value (was passed into hook on last render)
  const prevCount: number = usePrevious<number>(count);
  // Display both current and previous count value
  return (
    <div>
      <h1>
        Now: {count}, before: {prevCount}
      </h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
// Hook
function usePrevious<T>(value: T): T {
  // The ref object is a generic container whose current property is mutable ...
  // ... and can hold any value, similar to an instance property on a class
  const ref: any = useRef<T>();
  // Store current value in ref
  useEffect(() => {
    ref.current = value;
  }, [value]); // Only re-run if value changes
  // Return previous value (happens before update in useEffect above)
  return ref.current;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: check token balance of an address in js 
Javascript :: livewire multiple root elements detected. this is not supported 
Javascript :: stringToCapital.js 
Javascript :: Has many belongs to database relations nodejs 
Javascript :: pnpm tailwind react 
Javascript :: javascript auto complete not working 
Javascript :: Backbone Notes Miscellaneous 
Javascript :: Backbone Model And Collection 
Javascript :: how to validate date in react js 
Javascript :: using nodeenv 
Javascript :: base64-XMLHttpRequest 
Javascript :: React Gotchas 
Javascript :: How to Check if an Item is in an Array in JavaScript Using Array.includes() Starting From a Specified Index 
Javascript :: remove duplicate node 
Javascript :: javascript tree search 
Javascript :: clear console javascript 
Javascript :: javascript invert number 
Javascript :: window location href 
Javascript :: comment field react 
Javascript :: switch statement javascript 
Javascript :: calculate jwt expire time 
Javascript :: upload text file react js functional component 
Javascript :: vscode module path aliases 
Javascript :: javascript Non-numeric String Results to NaN 
Javascript :: navlink react active class 
Javascript :: freecodecamp javascript basic step quoting string 
Javascript :: actionscript random randomfunction 
Javascript :: how to check if a number is divisible by 3 and 5 in javascript 
Javascript :: roman to integer fastest way 
Javascript :: phaser rotate around x y point 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =