useEffect() Hook in React js
React's useEffect() Hook
The Effect Hook lets you perform side effects in function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount()
, componentDidUpdate()
and componentWillUnmount()
lifecycle methods.
Side-effects are things you want your application to make like:
- Fetching data
- Manually changing the DOM (document title)
- Setting up a subscription
Effects will run after every render, including the first render.
useEffect is a hook for encapsulating code that has 'side effects', if you are familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined,
Ex:
import React, {useState, useEffect} from 'react';
useEffect(Function)
useEffect(Function,Array)
- The function passed to useEffect will run after thee render is comitted to the screen
- Second argument to useEffectt that is the array of values that the effect depends on.
- You can call useEffects as many times as you want.
When using the the Effect Hook, we use useEffect()
:
Running an Effect Hook only when something changes
Since useEffect()
runs every time a component renders, how do we get it to only run once, on mount? The Effect Hook can take a second argument, an array. It will look through the array and only run the effect if one of those values has changed.
componentDidMount: Runs once
// only run on mount. pass an empty array useEffect(() => { // only runs once }, []);
componentDidUpdate: Runs on changes
// only run if count changes useEffect( () => { // run here if count changes }, [count] );
Hooks Effect :
The Effect Hook allows us to perform side effects in the function components. It does not use components lifecycle methods which are available in class components. In other words, Effects Hooks are equivalent to componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle methods.
Here is the clear example of useEffect() , it side effects to document.title
Hooks Effect : with array []
API fetch using useEffect()
API integration with useEffect(); using Material Table: