Skip to content

Instantly share code, notes, and snippets.

@krutoo
Last active April 8, 2020 09:49
Show Gist options
  • Save krutoo/0d55d7bc8aee91028e0a012f582a181f to your computer and use it in GitHub Desktop.
Save krutoo/0d55d7bc8aee91028e0a012f582a181f to your computer and use it in GitHub Desktop.
Custom react hooks
import isEqual from 'lodash/isEqual';
import { useState, useEffect, useRef, useMemo as defaultUseMemo } from 'react';
export const useOnMount = callback => {
useEffect(callback, []);
};
export const useForceUpdate = () => {
const [, setState] = useState(null);
return () => setState(Math.random());
};
export const useOnUpdate = callback => {
const isInitialUpdate = useRef(true);
useEffect(() => {
if (isInitialUpdate.current) {
isInitialUpdate.current = false;
} else {
callback();
}
});
};
export const useOnUnmount = callback => {
useEffect(() => () => callback(), []);
};
export const useConstant = (calculateValue, dependencies) => {
const { current: memoFn } = useRef(calculateValue);
const { current: memoDeps } = useRef(dependencies);
const { current: memoValue } = useRef(memoFn(memoDeps));
return memoValue;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment