The usePrevious Hook is a simple Hook that lets us get the previous value of a prop or Hook value. It will always store and return the previous value of any given variable, and it works as follows:
- First, we import the useState and usePrevious Hooks:
import React, { useState } from 'react'
import { usePrevious } from 'react-hookedup'
- Then, we define our App component, and a Hook in which we store the current count state:
export default function UsePrevious () {
const [ count, setCount ] = useState(0)
- Now, we define the usePrevious Hook, passing the count value from the State Hook to it:
const prevCount = usePrevious(count)
The usePrevious Hook works with any variable, including component props and values from other Hooks.
- Next, we define a handler function, which will increase count by 1:
function handleClick () {
setCount(count + 1)
}
- Finally, we render the previous value of count, the current value of count, and a button to increase count:
return (
<div>
Count was {prevCount} and is {count} now.
<button onClick={handleClick}>+1</button>
</div>
)
}
The previously defined component will first show Count was and is 0 now., because the default value for the Previous Hook is null. When clicking the button once, it will show the following: Count was 0 and is 1 now..