Created
April 3, 2023 03:57
-
-
Save jhavenz/b722de306741caf146b622dfbe8a81ab to your computer and use it in GitHub Desktop.
usePreviousState React hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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