Today, I am learning useEffect hooks in react for my project.
- Triggering on every render.
useEffect(()=>{
console.log("I re-render");
});
- Triggering on the first render/mount only (componentDidMount).
useEffect(()=>{
console.log("The component mounted");
},[]);
- Triggering on the first render + whenever dependency changes (componentDidUpdate).
const [name,set_name] = useState("John Doe");
useEffect(()=>{
console.log("The name changed");
},[name]);
- Triggering on unmounting of a component (componentWillUnmount).
useEffect(()=>{
window.addEventListener("resize",updateWindowWidth);
return ()=>{
// when component will unmount, this cleanup code will run.
window.removeEventListener("resize",updateWindowWidth);
}
},[])