22
loading...
This website collects cookies to deliver better user experience
useEffect hook
lets you perform side effects in functional components.React class lifecycle
methods, you can think of useEffect hook
as componentDidMount
, componentDidUpdate
and componentWillUnmount
combined.hook
, you let React know that your component needs to perform something after rendering of the component. React will remember the function which you passed and react call it after performing the DOM updates.import React from "react";
class ExampleComponent {
//After rendering
componentDidMount() {
document.title = "Updating the title in componentDidMount";
}
//After updating
componentDidUpdate() {
document.title = "Updating the title in componentDidUpdate";
}
render() {
return <div>Setting the title</div>;
}
}
export default ExampleComponent;
import React, { useEffect } from "react";
const ExampleComponent = () => {
useEffect(() => {
document.title = "Setting title using useEffect";
});
return <div>Setting the title using useEffect hook</div>;
};
useEffect(() => {
console.log(
"I will be called each time the component renders and re-renders"
);
});
[]
is called the dependencies array. An empty array means no dependency.useEffect(() => {
console.log("I will be called only once when the component is mounted");
}, []);
useEffect(() => {
console.log("I will be called first when the component is mounted and each time the name is changing");
}, [name]);
useEffect(() => {
// some tasks
return () => {
console.log("I do cleanups");
console.log(
"will first run on component mount then, will run before useEffect and lastly before unmounting"
);
};
});