Effect Hook 1) is a hook that lets you perform side effects in functional components, and is similar to lifecycle methods in classes.
An effect is also known as a side-effect
Example of effect:
The function that is passed is also called an effect
By default, an effect is executed after every render (regardless of whether the component just mounted, or if it has been updated)
Updating at the same time, the page and the document.title
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = React.useState(0);
// Similar to componentDidMount and componentDidUpdate:
React.useEffect(() => {
// Update the document title using the browser API
let doc = window.document
if (inIframe){
doc = window.parent.document;
}
doc.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
ReactDOM.render(
<Example/>,
document.getElementById('root')
);
<div id="root"></div>
Effects are scheduled with:
synchronous
The function returned by an effect is called the cleanup function.
This function is executed when the component Unmount and Update. See lifecycle demo
You can still skip the cleanup for update for perf reason. See skip
When you want to run the function only once, pass an empty array. Because the value will never change, the function will never run again.
Example with a google analytics on a page level that log a page view.
React.useEffect(() => {
initGA();
logPageView();
Router.events.on('routeChangeComplete', logPageView);
}, []);