Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Using the useEffect hook

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
1.86 mins read

The useEffect hook allows us to perform side effects in functional components. Side effects include things like fetching data, subscribing to events, or manually changing the DOM, which are operations that can't be done directly during the rendering phase.

It lets us express how our component should react to changes in its dependencies (props or state) or perform actions when the component is mounted or unmounted.

We can use the useEffect hook in a React functional component as mentioned below -

  • Firstly, we have to import it.

import React, { useEffect } from 'react';

  • Secondly, Create the functional component and use the useEffect hook.


     function MyComponent() {
       // State variable
       const [data, setData] = useState([]);
     
       // Effect hook
       useEffect(() => {
         fetchData();
         
         return () => {
           // Perform cleanup here if needed (e.g., remove event listeners, unsubscribe,        etc.).
         };
       }, [data]); // Pass the dependencies array here. If empty, the effect runs only        once after the initial render.
     
       const fetchData = async () => {
         // Example of fetching data from an API using fetch or any other library
         const response = await fetch('https://api.example.com/data');
         const data = await response.json();
         setData(data);
       };
     
       return (
         <div>
           {/* Render the component using the 'data' state */}
           <ul>
             {data.map(item => <li key={item.id}>{item.name}</li>)}
           </ul>
         </div>
       );
     }
    

In this example, we have a MyComponent functional component that uses the useState hook to maintain a data state variable. We use the useEffect hook to perform the data fetching operation and update the data state whenever the component is mounted or the data state changes.



The effect function inside useEffect is executed after the component is rendered and the DOM is updated. It's important to pass the dependency array as the second argument to useEffect.

The cleanup function returned inside useEffect is optional but useful when we need to clean up any resources or subscriptions that were set up during the effect's execution. The cleanup function is executed when the component is unmounted or when the dependencies change before the next effect is run.

The useEffect hook is a powerful tool to manage side effects in functional components and is one of the essential hooks in React development.

Library

WEB DEVELOPMENT

Basic

Frontend

Express JS

React

Hello World in ReactJS

Rendering Elements

States and Lifecycles in React JS

Handling Events in React JS

Introduction to JSX

Components and Props in React JS

Conditional Rendering

Lists and Keys in React JS

Introduction to Redux

Types of components (class vs functional)

Using the useEffect hook

Building custom hooks in React JS

Context API in React JS

Forms in React JS

Lifting State Up in React JS

Composition vs Inheritance

Prop drilling in React JS

Introduction to Hooks

Using the useState hook

UseMemo vs useCallback

Backend

Interview Questions

FAANG QUESTIONS