Docs
Latest

Latest

Returns the latest value, effectively avoiding the closure problem and unnecessary re-renders

About

The useLatest hook is a custom React hook that provides a way to always access the most recent value of a given variable. This can be particularly useful in scenarios where you need to ensure that a value is always up-to-date within callbacks or effects, without triggering unnecessary re-renders.

Parameters

NameTypeDescription
valueTThe value for which the latest reference is to be maintained. The generic type T allows this hook to be used with any data type.

Return Values

NameTypeDescription
refReact.MutableRefObject<T>A mutable reference object whose .current property is always updated to the latest value provided to the hook.

Installation

Run the following command:

npx scriptkavi-hooks@latest add latest

Usage

import { useLatest } from "@/hooks/latest"
import React, { useEffect } from "react"
 
function ExampleComponent({ value }) {
  const latestValueRef = useLatest(value)
 
  useEffect(() => {
    const interval = setInterval(() => {
      console.log(latestValueRef.current) // Always logs the latest value
    }, 1000)
 
    return () => clearInterval(interval)
  }, [latestValueRef])
 
  return <div>Current value: {value}</div>
}