Skip to content

Instantly share code, notes, and snippets.

@codemile
Created January 2, 2025 17:00
Show Gist options
  • Save codemile/9c3574ddfa52ee6eff736803beba3c8e to your computer and use it in GitHub Desktop.
Save codemile/9c3574ddfa52ee6eff736803beba3c8e to your computer and use it in GitHub Desktop.
Custom React hook to maintain a stable reference for an array when its values change
import {useEffect, useState} from 'react';
export function useStableArray<TType>(
items?: Array<TType>
): Array<TType> | undefined {
const [stableArray, setStableArray] = useState<Array<TType>>(items);
useEffect(() => {
if (JSON.stringify(items) !== JSON.stringify(stableArray)) {
setStableArray(items);
}
}, [items, stableArray]);
return stableArray;
}
@codemile
Copy link
Author

codemile commented Jan 2, 2025

You could also avoid rerenders using a ref, and also use isEqual from lodash (which is faster), but I like the above because it's easy to read and understand.

import isEqual from 'lodash.isequal';
import {useRef} from 'react';

export function useStableArray<TType>(items?: Array<TType>): Array<TType> | undefined {
    const [stableArray, setStableArray] = useState<Array<TType>>(items);
    const prevItemsRef = useRef(items);

    useEffect(() => {
        if (!isEqual(prevItemsRef.current, items)) {
            setStableArray(items);
            prevItemsRef.current = items;
        }
    }, [items]);

    return stableArray;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment