Pull to refresh

React Custom Hook: usePrevious

Level of difficultyMedium
Reading time2 min

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 (
                {count} - {previousCount}
            <button onClick={() => setCount(currentCount => currentCount + 1)}>
            <button onClick={() => setName("John")}>Change Name</button>

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://habr.com/en/articles/746760/

Total votes 2: ↑1 and ↓1+1