In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "usePrevious" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.
Github: https://github.com/sergeyleschev/react-custom-hooks
import { useRef } from "react"
export default function usePrevious(value) {
const currentRef = useRef(value)
const previousRef = useRef()
if (currentRef.current !== value) {
previousRef.current = currentRef.current
currentRef.current = value
}
return previousRef.current
}
The advantages of using usePrevious are remarkable. By using useRef, this hook efficiently stores the current and previous values, updating them whenever the value changes. By comparing the current and previous values, you can easily detect and respond to changes in your component's data.
This custom hook can be a game-changer in various scenarios. For instance, you can utilize usePrevious to compare and visualize changes in data, track state transitions, or implement undo/redo functionality. Additionally, it can be valuable in form handling, animations, and any situation where having access to the previous value is crucial for your application's logic.
Let's take a glance at how usePrevious can be used in practice. Consider a React component called PreviousComponent, where we have a count state, a name state, and a button to increment the count and change the name. By incorporating usePrevious, we can effortlessly display the current count alongside its previous value, enabling users to visualize the count's changes at a glance.
import { useState } from "react"
import usePrevious from "./usePrevious"
export default function PreviousComponent() {
const [count, setCount] = useState(0)
const [name, setName] = useState("Sergey")
const previousCount = usePrevious(count)
return (
<div>
<div>
{count} - {previousCount}
</div>
<div>{name}</div>
<button onClick={() => setCount(currentCount => currentCount + 1)}>
Increment
</button>
<button onClick={() => setName("John")}>Change Name</button>
</div>
)
}
Throughout this article series, we focused on one of the gems from the collection of React custom hooks – "usePrevious". This hook, sourced from the "react-custom-hooks" repository, revolutionizes how we work in our React applications.
Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4
Oldest comments (4)
Nice read!
Thank you, Mitchell! I'm glad you enjoyed the article. 📚👍
Simple read thanks 🙏🏽
You're welcome! Happy coding! 🚀💻