Last active
June 22, 2022 20:19
-
-
Save olegchursin/11b0bb030443e4071ab91a604e8c380c to your computer and use it in GitHub Desktop.
Use useEffect right
This file contains 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
// Fire useEffect only once on mount | |
cosnt executedRef = useRef(false); | |
useEffect(() => { | |
if(executedRef.current) { | |
return; | |
} | |
// doSomething(); | |
executedRef.current = true; | |
}, []); | |
// Fetch data | |
const Component: React.FC<T> = () => { | |
const [data, setData] = useState(null); | |
useEffect(() => { | |
let cancelled = false; | |
fetch('some/resource').then(data => { | |
if(cancelled) { | |
return; | |
} | |
setData(data); | |
}); | |
return () => { cancelled = true }; | |
}, []) | |
return // .. | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment