
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ReactJS useLayoutEffect Hook
In this article, we are going to see how to set up side-effects or HTTP requests in a functional component.
This hook has the similar functioning like that of useEffect hooks but rather than being called out asynchronously, it has a synchronous effect. This hook is used to load the data in the DOM synchronously and also works in the same phase like that of useEffect hook.
Note: Use useLayoutEffect hook only if useEffect hooks don't give the expected output.
Syntax
useLayoutEffect()
Example
In this example, we will build a React application that displays and updates the name synchronously.
App.jsx
import React, { useLayoutEffect, useState } from 'react'; const App = () => { const [name, setName] = useState('Rahul'); useLayoutEffect(() => { if (name === 'Rahul') { setName('Bansal'); } }, [name]); return <div>{name} has email id of [email protected]</div>; }; export default App;
In the above example, useLayoutEffect hook is called synchronously and hence updated the state before the component is being mounted.
Output
This will produce the following result.
Advertisements