Skip to content

Instantly share code, notes, and snippets.

@jhavenz
Created April 3, 2023 03:57
Show Gist options
  • Save jhavenz/b722de306741caf146b622dfbe8a81ab to your computer and use it in GitHub Desktop.
Save jhavenz/b722de306741caf146b622dfbe8a81ab to your computer and use it in GitHub Desktop.
usePreviousState React hook
import React, { useRef } from 'react'
export default function usePreviousState(value) {
const currentRef = useRef(value)
const previousState = useRef()
if (currentRef.current !== value) {
previousState.current = currentRef.current
currentRef.current = value
}
return previousState.current
}
import usePreviousState from '@/hooks/usePreviousState/usePreviousState'
import React, { useState } from 'react'
export default function UsePreviousStateExampleComponent() {
const [count, setCount] = useState(0)
const [name, setName] = useState('Jimbo')
const previousCount = usePreviousState(count)
return (
<div>
<div>
{count} - {previousCount}
</div>
<div>{name}</div>
<button
onClick={() => setCount((currentCount) => currentCount + 1)}>
Increment
</button>
<button onClick={() => setName('Jane Doe')}>Change Name</button>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment