React useEffect

useEffect is a React Hook that lets you synchronize a component with an external system.

useEffect and fetch() example:


const PostList = ({ posts }) => {

  return (

    <div>

      {posts.map((post, index) => (

        <div key={index}>

          <h3>{post.title}</h3>

          <div>{post.body}</div>

        </div>

      ))}

    </div>

  );

};

export default PostList;



// Usage

import { useState, useEffect } from 'react';



const App = () => {

  const [posts, setPosts] = useState([]);

  const [loading, setLoading] = useState(true);



  useEffect(() => {

    const fetchData = async () => {

      try {

        const response = await fetch('https://jsonplaceholder.typicode.com/posts');

        if (!response.ok) {

          throw new Error('Failed to fetch data');

        }

        const data = await response.json();

        setPosts(data);

      } catch (error) {

        console.error('Error fetching data:', error);

      } finally {

        setLoading(false);

      }

    };



    fetchData();

  }, []);



  return (

    <div>{loading ? <p>Loading...</p> : <PostList posts={posts} />}</div>

  );

};

export default App;

useEffect and axios example:


const PostList = ({ posts }) => {

  return (

    <div>

      {posts.map((post, index) => (

        <div key={index}>

          <h3>{post.title}</h3>

          <div>{post.body}</div>

        </div>

      ))}

    </div>

  );

};

export default PostList;



// Usage

import { useState, useEffect } from 'react';

import axios from 'axios';



const App = () => {

  const [posts, setPosts] = useState([]);

  const [loading, setLoading] = useState(true);



  useEffect(() => {

    const fetchData = async () => {

      try {

        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');

        setPosts(response.data);

      } catch (error) {

        console.error('Error fetching data:', error);

      } finally {

        setLoading(false);

      }

    };



    fetchData();

  }, []);



  return (

    <div>{loading ? <p>Loading...</p> : <PostList posts={posts} />}</div>

  );

};

export default App;

useEffect(): for optimizing performance.


import { useState, useEffect } from 'react';

const PerformanceComponent = ({ propValue }) => {

  const [stateValue, setStateValue] = useState('');



  useEffect(() => {

    const result = doExpensiveComputation(propValue);

    setStateValue(result);

  }, [propValue]); // Re-run if propValue changes



  return (

    <div>{stateValue}</div>

  );

};

export default PerformanceComponent;

useEffect(): TimerComponent with cleanup calback.


import { useState, useEffect } from 'react';

const TimerComponent = () => {

  const [count, setCount] = useState(0);



  useEffect(() => {

    const interval = setInterval(() => {

      setCount(prevCount => prevCount + 1);

    }, 1000);



    return () => clearInterval(interval);

  }, []);



  return (

    <p>Count: {count}</p>

  );

};

export default TimerComponent;

Timer component done incorrectly and will create infinite loop (using simple setCount syntax and no cleanup function)


import { useState, useEffect } from 'react';

const TimerComponent = () => {

  const [count, setCount] = useState(0);



  useEffect(() => {

    const interval = setInterval(() => {

      setCount(count + 1);

    }, 1000);

  }, []);



  return (

    <p>Count: {count}</p>

  );

};

export default TimerComponent;

Leave a Comment