xxxxxxxxxx
Load external data or interact outside of the component
xxxxxxxxxx
What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed, and call it later after performing the DOM updates.
xxxxxxxxxx
most common cases how useEffect implementation:
- fetch data from API,
- directly updating the DOM,
- use timers and real-time data displays (such as BTC current price)
- validating input field
- trigger animation on new array value
-
// 1- EVERY RERENDER
useEffect( () => {
console.log("It runs everytime this component rerenders")
});
// 2- ON MOUNT
useEffect( () => {
console.log("It Only runs once (When the component gets mounted)")
}, []);
// 3- DEPENDING ON CONDITION
useEffect( () => {
console.log("It runs everytime the condition is changed")
}, [condition]); //basically the dependency array determines when the rerender happens
// 4- DEPENDING ON CONDITION, BUT WITH "clean up"
useEffect( () => {
console.log("It runs everytime my condition is changed")
return () => {
console.log("Use this return as a 'clean up tool' (it runs before the actual code)")
}
}, [condition]);
xxxxxxxxxx
If you’re familiar with React class lifecycle methods,
you can think of useEffect Hook as componentDidMount,
componentDidUpdate, and componentWillUnmount combined.
xxxxxxxxxx
useEffect is a hook for encapsulating code that has 'side effects,' and is like a combination of componentDidMount , componentDidUpdate , and componentWillUnmount . Previously, functional components didn't have access to the component life cycle, but with useEffect you can tap into it.23.1.2019