Last active
September 18, 2020 10:20
-
-
Save dartmax/c80a424d28974a10bec6ffbb1b2d9d68 to your computer and use it in GitHub Desktop.
Custom Hook for second rendering useEffect as componentDidUpdate without asinc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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