useUpdateEffect
Just like useEffect but runs only when anything in the array of dependencies change. Doesn’t run on mount.
Installation
npx rabbithook@latest add use-update-effect
Usage
import useUpdateEffect from "@/hooks/use-update-effect";
function Component() { const [count, setCount] = useState(0);
useUpdateEffect(() => { // Will not run on mount
console.log("Count changed: ", count); /* 1, 2, 3, 4, 5, ... */ }, [count])
return ( <> <p>Count: { count }</p>
<button onClick={() => setCount(count + 1)}>Increment</button> </> );}
Code
import { useRef, useEffect } from "react"
function useUpdateEffect(callback: Function, dependencies: any[]) { const firstRenderRef = useRef(true);
useEffect(() => { if (firstRenderRef.current) { firstRenderRef.current = false; return; }
return callback(); }, dependencies)}
export default useUpdateEffect;
import { useRef, useEffect } from "react"
function useUpdateEffect(callback, dependencies) { const firstRenderRef = useRef(true);
useEffect(() => { if (firstRenderRef.current) { firstRenderRef.current = false; return; }
return callback(); }, dependencies)}
export default useUpdateEffect;