Last active
March 12, 2026 03:48
-
-
Save krutoo/c5bf6a9ea73e0c8cfbf8b0ea26fa5242 to your computer and use it in GitHub Desktop.
React hook to run callback when dependency changes (like useEffect but during render)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { type DependencyList, type EffectCallback, useRef } from 'react'; | |
| /** | |
| * Calls callback immediately (during render) if dependencies changed since last render. | |
| * Useful when you don't need to wait for DOM changes. | |
| * Based on this article: https://react.dev/learn/you-might-not-need-an-effect. | |
| * @param callback Callback. | |
| * @param deps Dependency list. | |
| */ | |
| export function useInstantEffect(callback: EffectCallback, deps: DependencyList): void { | |
| const depsRef = useRef<DependencyList>(null); | |
| const resetRef = useRef<ReturnType<EffectCallback>>(null); | |
| if (!depsRef.current || !isArraysShallowEqual(deps, depsRef.current)) { | |
| resetRef.current?.(); | |
| depsRef.current = deps; | |
| resetRef.current = callback(); | |
| } | |
| } | |
| /** | |
| * Checks that array is shallow equal to another. | |
| * @param a Array. | |
| * @param b Array. | |
| * @returns Boolean. | |
| */ | |
| function isArraysShallowEqual(a: readonly unknown[], b: readonly unknown[]): boolean { | |
| if (Object.is(a, b)) { | |
| return true; | |
| } | |
| if (a.length !== b.length) { | |
| return false; | |
| } | |
| for (let i = 0; i < a.length; i++) { | |
| if (!Object.is(a[i], b[i])) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment