Skip to main content

useUpdatedEffect

useUpdatedEffect is a custom React hook that behaves like useEffect but skips the initial render, running the effect only on subsequent dependency updates.

Usage

import { useState } from "react";
import { useUpdatedEffect } from "hookify-react";

export default function UseUpdatedEffectExample() {
const [count, setCount] = useState(0);

useUpdatedEffect(() => {
console.log("Effect triggered due to dependency change:", count);

return () => {
console.log("Cleanup for:", count);
};
}, [count]);

return (
<div style={{ textAlign: "center", fontFamily: "Arial, sans-serif" }}>
<h2>useUpdatedEffect Hook Example</h2>
<p>Count: <strong>{count}</strong></p>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
<p>The effect runs on updates, not on the first render.</p>
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
effectEffectCallbackThe effect function to execute on dependency updates. May return a cleanup function, just like useEffect.
depsDependencyListThe array of dependencies to track for changes.

Return Value

PropertyTypeDescription
voiduseUpdatedEffect does not return a value.

Behavior

  • Behaves like useEffect, but skips the initial render.
  • Runs the effect only on subsequent renders when the dependencies change.
  • Supports returning a cleanup function from the effect, exactly like useEffect.