This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

React Insights : Choosing Between useLayoutEffect and useEffect

  • ReactJS
  • November 14, 2024

Share On :

Introduction
useEffect and useLayoutEffect are two React hooks used to manage side effects in a React component. When building React applications, understanding when to use useEffect versus useLayoutEffect can significantly impact your app’s performance and user experience. Both hooks serve to handle side effects in functional components, but they behave differently during the rendering process. Let’s dive deeper into how they work, their differences, and some practical examples.
Prerequisites
  • Node.js and npm
  • React
  • Typescript
  • React Hooks
What is useEffect?
useEffect is a commonly used hook that allows you to perform side effects in functional components. Side effects could be anything that affects things outside of your component, such as data fetching, DOM manipulation, or logging. useEffect is designed to run after the render is committed to the screen.The useEffect hook in React takes two arguments:
  • Callback function : This function contains the side-effect code that you want to execute.
  • Optional dependency array : The callback function is called only when any of the values in this array change. If no dependencies are specified, the callback runs after every render.
By using dependencies, you can control when the side effect should be re-executed, optimizing the component’s performance.
When to use
In most cases, useEffect should be your go-to hook for handling side effects. Here are some scenarios where useEffect is more appropriate:
  • Data fetching : Trigger an API call after the component mounts.
  • Adding event listeners : For events like scroll or resize.
  • Updating non-UI state : Updating states that don’t impact the immediate layout.
Syntax
				
					useEffect(() => {
  // Side effect function
}, [dependencies]);


				
			

Here are some examples of how to use useEffect:

  1. useEffect with an Empty Dependency Array : This runs only once when the component mounts, like componentDidMount.
				
					
import React, { useEffect } from 'react';
function UseEffectWithEmptyArray() {
  useEffect(() => {
    console.log('Component mounted!');
  }, []); // Empty array ensures it only runs once
  return <div>Check the console to see the mount message.</div>;
}


				
			
  1. useEffect with Specific Dependencies : This will run whenever the specified dependencies change.
				
					
import React, { useState, useEffect } from 'react';
function UseEffectWithDependencies() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log(`Count changed: ${count}`);
  }, [count]); // Runs only when `count` changes
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
    </div>
  );
}


				
			
  1. Cleaning up in useEffect : If the effect returns a cleanup function, it will run when the component unmounts or before the next effect runs.
				
					
import React, { useState, useEffect } from 'react';

function TimerComponent() {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((prevSeconds) => prevSeconds + 1);
    }, 1000);
    return () => {
      clearInterval(interval); // Cleanup to avoid memory leaks
    };
  }, []); // Empty dependency array, runs only on mount and unmount
  return <div>Timer: {seconds} seconds</div>;
}


				
			
What is useLayoutEffect?

useLayoutEffect is similar to useEffect, but it runs synchronously after all DOM mutations and before the browser paints. This hook is crucial when you need to perform DOM measurements or manipulate the layout synchronously because it guarantees that the effect will run before the user sees any visual changes.

The useLayoutEffect hook in React takes two arguments:

  • Effect function : This function contains the effect code that you want to run after the DOM has been updated but before the browser has been painted.
  • Optional dependency array : The effect function is only called when any of the values in this array change. If no dependencies are specified, the effect will run after every render.

This hook is similar to useEffect, but it fires synchronously after all DOM mutations. It can be useful for effects that need to interact with the layout before the screen is updated.

When to use

Use useLayoutEffect when you need to make changes that affect the layout or DOM measurements before the user sees them. Some common scenarios include::

  • Measuring elements : Getting the dimensions of an element and setting the layout accordingly.
  • Synchronous DOM manipulation : Ensuring that any changes are applied before the user sees them.

Syntax

				
					useLayoutEffect(() => {
// runs synchronously after commit
return () => {
// cleanup
}}, [input])


				
			
Comparison useEffect Vs useLayoutEffect

Features

useEffect

useLayoutEffect

Execution Timing

Runs asynchronously after the render is painted to the screen.

Runs synchronously after the DOM is updated but before the browser paints.

Use Cases

Non-blocking side effects like data fetching, adding event listeners, or updating non-UI state.

DOM measurements, layout adjustments, or any visual updates are required before the user sees the component.

Performance Impact

Doesn’t block rendering; allows the UI to load faster.

Can block the paint until it completes, which might slow down the initial render if overused.

Ideal for

Side effects that do not affect layout or visual presentation immediately.

Effects that impact layout, positioning, or require accurate DOM measurements before the component is shown.

Common Examples

API requests, setting up event listeners (e.g., scroll, resize), logging.

Measuring dimensions of elements, synchronizing animations, or making visual adjustments before paint.

Frontend Setup in React 

We’ll write the code to get a better understanding of useEffect and useEffectLayou hooks.

Step-by-step Implementation

  1. Create a React App

Let’s create a React app using the following command:

				
					/Create a react app using the following command

npx create-react-app react-hooks-app --template typescript

				
			

    After the setup is complete, navigate to your project folder:

				
					// Navigate to the project folder
 cd react-hooks-app
 npm start
				
			

This will launch the development server, and you’ll be able to view the app at http://localhost:3000.

  1. Project Structure

Make sure your project has the following folder structure:

Image1 3 1 | React Insights : Choosing Between useLayoutEffect and useEffect
  1. useEffect() Hooks Example

We’ll create a standalone UseEffectExample component within the components folder. This component will include a search feature that dynamically filters a list of users based on the search input. 

Using the useEffect hook, we’ll monitor changes in the search query to update the filtered user list in real-time. This approach demonstrates how useEffect can be effectively used to handle initial data fetching and to perform live filtering as the user types.

				
					// UseEffectExample.tsx
import React, { useState, useEffect } from 'react';

interface User {
  id: number;
  name: string;
}

const UseEffectExample: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [searchQuery, setSearchQuery] = useState<string>('');

  // Fetch users on component mount
  useEffect(() => {
    const fetchUsers = async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const data: User[] = await response.json();
      setUsers(data);
      setFilteredUsers(data); // Initially show all users
    };

    fetchUsers();
  }, []); // Empty dependency array to fetch data only on mount

  // Update filteredUsers when searchQuery changes
  useEffect(() => {
    const filtered = users.filter(user =>
      user.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
    setFilteredUsers(filtered);
  }, [searchQuery, users]); // Runs whenever searchQuery or users changes

  return (
    <div className='container'>
      <h3>useEffect Example</h3>
      <input
        type="text"
        placeholder="Search users"
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
      />
      <ul>
        {filteredUsers.map((user) => (
          <li key={user.id} className='user-name'>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default UseEffectExample;


				
			
    • Fetching Data : When the component mounts, useEffect fetches the list of users from an API and sets it in the users state.
    • Filtering Users : Another useEffect monitors searchQuery and users. Whenever the searchQuery changes, it filters the users to include only those whose names contain the search text.
    • Updating the Filtered List : The filtered results are stored in filteredUsers, which is then rendered in the component
  1. useLayoutEffect() Hooks Example

We’ll create a standalone LayoutEffectExample component within the components folder. 

				
					// LayoutEffectExample.tsx
import React, { useLayoutEffect, useRef, useState } from "react";

const LayoutEffectExample: React.FC = () => {
  const [width, setWidth] = useState<number>(0);
  const divRef = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    // Ensure divRef is defined before accessing clientWidth
    if (divRef.current) {
      const handleResize = () => {
        setWidth(divRef.current!.clientWidth);
      };

      // Set initial width
      handleResize();

      // Add resize listener
      window.addEventListener("resize", handleResize);

      // Cleanup event listener on unmount
      return () => window.removeEventListener("resize", handleResize);
    }
  }, []); // Empty dependency array to run only on mount/unmount

  return (
    <div className="container">
      <h3>useLayoutEffectEffect Example</h3>

      <div
        ref={divRef}
        className="div-container"
      >
        Resize the window to see changes
      </div>
      <p className='width-text'>Width of the div: {width}px</p>
    </div>
  );
};

export default LayoutEffectExample;


				
			
Here is a detailed explanation of the code
    • Ref for the element : divRef is a reference to the <div> element.
    • useLayoutEffect : Runs after DOM updates, allowing us to measure the element’s width before the browser repaints.
    • Event Listener : The resize event updates the width when the window resizes, and the cleanup removes the listener on component unmount.
    1. Integrating the Components into the App : Now, we’ll import UseEffectExample and LayoutEffectExample components into the main App.tsx file. This component will render the UI.
				
					
//App.tsx
import React from "react";
import "./App.css";
import UseEffectExample from "./components/UseEffectExample";
import LayoutEffectExample from "./components/LayoutEffectExample";

function App() {
  return (
    <>
      <LayoutEffectExample />
      <UseEffectExample />
    </>
  );
}
export default App;


				
			
Image2 1 | React Insights : Choosing Between useLayoutEffect and useEffect
Image3 | React Insights : Choosing Between useLayoutEffect and useEffect
Conclusion

Understanding when to use useEffect versus useLayoutEffect in React enhances performance and user experience. Use useEffect for non-blocking tasks like data fetching and event listeners, as it runs after rendering, ensuring faster load times. Use useLayoutEffect for layout-related tasks requiring synchronous execution after DOM updates but before painting, such as DOM measurements and layout adjustments.

Thoughtful use of these hooks improves performance, prevents layout shifts, and ensures a smoother user experience.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

March 27, 2024
Authentication and Authorization in React
September 6, 2024
Creating forms in React with React Hook Form
Creating forms in React with React Hook Form
September 13, 2024
Handling Large Data With Infinite Scrolling in React
Handling Large Data With Infinite Scrolling in React
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telecom Public Website _ Multilingual, E-Commerce, and Advanced Features
Telecom Public Website : Multilingual, E-Commerce, and Advanced Features

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram