Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Created June 14, 2026 16:54
Show Gist options
  • Select an option

  • Save aliakakis/7a03481fc0a19936d120d37d2eada3a7 to your computer and use it in GitHub Desktop.

Select an option

Save aliakakis/7a03481fc0a19936d120d37d2eada3a7 to your computer and use it in GitHub Desktop.
React Lifecycle Hooks
import { isEqual } from "lodash";
import { useEffect, useRef } from "react";
/**
* A hook that executes a callback function only once when the component is mounted.
*
* @param {Function} fn - The callback function to be executed during the component's mount phase.
* @return {void} This function does not return any value.
*/
export function useOnMount(fn: () => void) {
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(fn, []);
}
/**
* A React hook that executes a given function when the component unmounts.
*
* @param {Function} fn - The function to be executed on component unmount.
* @return {void} This hook does not return any value.
*/
export function useOnUnmount(fn: () => void) {
const fnRef = useRef(fn);
useEffect(() => {
fnRef.current = fn;
}, [fn]);
useEffect(() => () => fnRef.current(), []);
}
/**
* A React hook that monitors changes to the provided `props` and invokes a callback function `cb` when updates are detected.
*
* @param {T | Array<T>} props - The value or an array of values to monitor for updates.
* @param {(newValue: T | Array<T>, oldValue: T | Array<T>) => void} cb - The callback function to invoke when the monitored value(s) change. Receives the new value and the old value as arguments.
* @return {void} Does not return a value.
*/
export function useOnUpdate<T>(
props: T | Array<T>,
cb: (newValue: T | Array<T>, oldValue: T | Array<T>) => void,
): void {
const _props = Array.isArray(props) ? props : [props];
const propRef = useRef(_props);
const cbRef = useRef(cb);
const mountedRef = useRef(false);
cbRef.current = cb;
useEffect(() => {
if (!mountedRef.current) {
mountedRef.current = true;
return;
}
if (!isEqual(propRef.current, _props)) {
const oldValue = propRef.current;
propRef.current = _props;
cbRef.current(_props, oldValue);
}
}, _props);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment