Skip to content

Instantly share code, notes, and snippets.

@olegchursin
Last active June 22, 2022 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olegchursin/11b0bb030443e4071ab91a604e8c380c to your computer and use it in GitHub Desktop.
Save olegchursin/11b0bb030443e4071ab91a604e8c380c to your computer and use it in GitHub Desktop.
Use useEffect right
// 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