Skip to content

Instantly share code, notes, and snippets.

Last active August 28, 2021 19:25
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gragland/1ed713a68c770ea414c3b92ccf2bdd2f to your computer and use it in GitHub Desktop.
import { useState, useEffect, useRef } from 'react';
// Usage
function App() {
// State value and setter for our example
const [count, setCount] = useState(0);
// Get the previous value (was passed into hook on last render)
const prevCount = usePrevious(count);
// Display both current and previous count value
return (
<h1>Now: {count}, before: {prevCount}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
// Hook
function usePrevious(value) {
// 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 = useRef();
// 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;
Copy link

@manzoorwanijk can you give some example code?

Copy link

…are you doing something like?:

function Image({ src, ...props }){
  const prevSrc = usePrevious(src)
    ()=> {
      console.log(`src changed`, {to: src, was: prevSrc})
  return <img {...props} src={src}/>

Copy link

export default function usePrevious(value) {
  // ref value will always be like [prev, state]
  let ref = useRef([null, null]);

  // storing prev, state values
  // Return previous value
  return ref.current[0];

Copy link

@manikanta-kotha it seems like this could be simpler and work the same:

export default function usePrevious(value) {
  const ref = useRef();
  const prev = ref.current
  ref.current = value
  return prev;

…but it might be nice to always return the previous value. Even on subsequent renders. Like this:

export default function usePrevious(value) {
  const ref = useRef();
  if (ref.current !== value){
    ref.previous = ref.current
    ref.current = value
  return ref.previous;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment