Created
April 25, 2019 10:16
-
-
Save Akiyamka/bc9efee04d75feed00acf207f2fb73b6 to your computer and use it in GitHub Desktop.
Demonstrate false-positive eslint(react-hooks/exhaustive-deps) rule
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
import useID from './useID'; | |
// Custom effect for manage id from ui or URL | |
const [id, setId] = useID(data); | |
useEffect(() => { | |
setId(data.id); | |
}, [data, setId]); // <- As the function changes after we use it, it creates an infinite loop |
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
import { useEffect, useReducer } from 'react'; | |
function reducer(state, action) { | |
switch (action.type) { | |
case 'setFromUI': | |
urlManager.setUrlData({ id: action.id }); | |
return action.id | |
case 'setFromUrl': | |
return action.id | |
default: | |
return action.id; | |
} | |
} | |
export default function useID(data) { | |
const [currentID, dispatch] = useReducer(reducer, []); | |
const setIDFromUrl = id => dispatch({ type: 'setFromUrl', id }); | |
const setIDFromUI = id => dispatch({ type: 'setFromUI', id }); | |
useEffect(() => { | |
function handler(newId) { | |
setIDFromUrl(newId); | |
} | |
return urlManager.subscribe('id', handler); | |
}, [data]); | |
return [currentID, setIDFromUI]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment