useEffect hook
Table of Contents
https://react.dev/reference/react/useEffect
useEffect hook
useEffect
is a React Hook that lets you synchronize a component with an external system
.
useEffect is a hook in React that allows you to perform side effects in function components
.
There is no need for urban dictionary - basically any work outside of the component.
Some examples of side effects are:
- subscriptions,
- fetching data,
- directly updating the DOM,
- event listeners,
- timers, etc.
Details
// Why are we passing an empty array as the second argument?
// If the dependency array is empty [], useEffect runs only on initial render.
// If we remove the second argument, useEffect runs on re-renders too.
useEffect(() => {
console.log('hello from useEffect');
}, []);
- accepts two arguments (second optional)
- first argument - callback function
- second argument - dependency array
- by default, it runs on each render (initial and re-render)
- callback can’t return promise (so can’t make it async)
- This is ok because the callback function is using an async function
useEffect(() => { const someFunc = () => { await fetch } someFunc(); }, []);
- But the callback function itself cannot be async. This is not ok.
useEffect(async () => { someFunc(); }, []);
- This is ok because the callback function is using an async function
Sample implementations
https://github.com/explorer436/programming-playground/tree/main/react-playground