Skip to content

Instantly share code, notes, and snippets.

@dartmax
Last active September 18, 2020 10:20
Show Gist options
  • Select an option

  • Save dartmax/c80a424d28974a10bec6ffbb1b2d9d68 to your computer and use it in GitHub Desktop.

Select an option

Save dartmax/c80a424d28974a10bec6ffbb1b2d9d68 to your computer and use it in GitHub Desktop.
Custom Hook for second rendering useEffect as componentDidUpdate without asinc
//Custom hook
import { useEffect, useRef } from 'react';
const useEffectSkipFirst = (fn, depValue) => {
const isFirstRun = useRef(true);
useEffect(() => {
if (!isFirstRun.current) fn();
if (isFirstRun.current) {
isFirstRun.current = false;
}
}, [...depValue]);
};
export default useEffectSkipFirst;
//Test (jest/enzyme) custom hook
import React from 'react';
import { mount } from 'enzyme';
import useEffectSkipFirst from 'modules/core/hooks/useEffectSkipFirst';
describe('useEffectSkipFirst should not run effect at first render', () => {
const testFunction = jest.fn();
const WrapperComponent = ({ testProp }) => {
useEffectSkipFirst(() => {
testFunction();
}, [testProp]);
return (<div />);
};
const wrapper = mount(<WrapperComponent testProp={1} />);
it('useEffectSkipFirst skip effect on first render of component', () => {
expect(testFunction).toHaveBeenCalledTimes(0);
});
it('useEffectSkipFirst use effect on second render of component', () => {
wrapper.setProps({ testProp: 2 });
expect(testFunction).toHaveBeenCalledTimes(1);
});
});
//How to use
useEffectSkipFirst(()=>{
SetIsProfileValueDispatched(!isCharacterEmpty)
},[isCharacterEmpty])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment