ideas icon indicating copy to clipboard operation
ideas copied to clipboard

useOriginalCopy

Open otakustay opened this issue 4 years ago • 0 comments

This is an interesting hook to cast a custom equal object to reference equal, suppose we have a simple fetch component:

const View = ({params}) => {
    const [value, setValue] = useState(null);
    useEffect(
        () => {
            setValue(null);
            fetchResource(params).then(setValue);
        },
        [params]
    );

    return value && <span>{value}</span>
};

We'd like fetchResource to start only when params has a different content, "different object with same content" should not trigger a fetch, however useEffect compares params by its reference and will trigger fetch even they have the same content.

By introducing a simple useOriginalCopy hook:

const useOriginalCopy = <T>(value: T, equals: (x: T, y: T) => boolean): T => {
    const copy = useRef(value);
    if (!equals(copy.current, value)) {
        copy.current = value;
    }
    return copy.current;
};

We can retrieve back the first reference of params:

const View = ({params}) => {
    const [value, setValue] = useState(null);
    const originalParams = useOriginalCopy(params, deepEqual);
    useEffect(
        () => {
            setValue(null);
            fetchResource(originalParams).then(setValue);
        },
        [originalParams]
    );

    return value && <span>{value}</span>
};

otakustay avatar Nov 11 '19 05:11 otakustay