Back to React JS Course

React JS Course

useEffect is a React Hook used in functional components to perform side effects in components.

Side effects may include data fetching, subscriptions, or manually changing the DOM in React components.

It is similar to lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

For example,

import React, { useState, useEffect } from "react"; function Counter() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked count times`; }); return ( <div> <p>You clicked count times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }

Generally when we want to fetch data from backend api we do that in useEffect for example,

import React, { useState, useEffect } from "react"; import axios from "axios"; const GitHubRepos = () => { const [data, setData] = useState(); useEffect(() => { const fetchGithubData = async () => { const result = await axios(`https://api.github.com/users/orugantipraveen/repos`); setData(result.data); }; }, [data]); return ( <div className="App">{data && data.map((item) => <p>{item.name}</p>)}</div> ); }; export default GitHubRepos;

Points to be noted

  • Runs on every update
    useEffect(() => {});
  • Runs ONCE after initial rendering
    useEffect(() => {}, []);
  • Runs ONCE after initial rendering and after every rendering ONLY if dependency changes.
    useEffect(() => {}, [Dependencies]);