About
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:
- Setting up a subscription,
- Manually changing the DOM in React components
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)
- effect can be skipped
Example
Counter
Updating at the same time, the page and the document.title
- The component
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>
);
}
- Just to detect an iframe to be able to get the top document in embedded code
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
- The rendering part
ReactDOM.render(
<Example/>,
document.getElementById('root')
);
- The root element where React will render
<div id="root"></div>
Lifecycle
Syntax
Effects are scheduled with:
- useEffect
- or useLayoutEffect
useEffect
useLayoutEffect
synchronous
Effect vs Class LifeCycle Method
- Asynchronous UI update - Unlike componentDidMount or componentDidUpdate, useEffect effects don’t block the browser from updating the screen. In the uncommon cases where they do (such as measuring the layout), there is a separate useLayoutEffect Hook with an API identical to useEffect.
- Resource release: A release of the resource happens in a the componentWillUnmount method whereas in a function, it happens with the cleanup function
- No update code: There is no special place for handling updates (componentDidUpdate) because the useEffect code is run on mount and update.
Management
Skip
Cleanup
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
Run once
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);
}, []);