- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - useLayoutEffect Hook
The new hook ‘useLayoutEffect’ is introduced in the version of React 18. This hook can be passed in the render function of a component to force the react library to consider the page's layout and adjust its calculations for things like spacing and overflow.
In simple terms, It is useful when we need to inspect how different elements of a web page look and then make changes based on what we discover. It operates quickly allowing changes to be made before the web page is visually updated. This contributes to a more fluid and responsive user experience. In terms of when it runs, it's comparable to o componentDidMount and componentDidUpdate methods, except it is for functional components in React rather than class components. It makes certain that modifications are made before the browser displays the updates.
Syntax
useLayoutEffect(setup, deps)
Parameters
setup − This is where you place the code that runs when your React component is added to a web page.
deps − Dependencies serve as a checklist of the elements on which our setup code is dependent. It can be anything from outside our component like information, data or something we generate within the component.
Return Value
It returns undefined.
How to use it?
The useLayoutEffect hook in React accepts two parameters. The first parameter is an effect function, while the second parameter is an array of dependencies. The first parameter, effect, is usually undefined or returns a cleanup function. The useLayoutEffect function signature is seen in the following code −
import React, { useLayoutEffect } from "react"; const App = props => { useLayoutEffect(() => { //Perform an action and either return undefined or clean up function. return () => { //Do clean up here }; }, [dependencies]); };
The useLayoutEffect hook is a powerful React component that allows us to direct where the input focus goes while rendering. This capability can be used to implement a wide range of user interactions, from hiding information to creating a dropdown menu. It allows us to fully customize what occurs behind the scenes with only one line of code.
Examples
Example − Simple User Input App
This app consists of a simple input field. As we type into the input, the entered value is immediately logged. It uses React.useLayoutEffect to capture and display the input value in real-time, providing a dynamic interaction with the user's input.
import React from "react"; function App() { const [value, setValue] = React.useState(""); React.useLayoutEffect(() => { console.log("Input value: ", value); }, [value]); return ( <div> <input type="text" value={value} onChange={(e) => setValue(e.target.value)} /> <p>You typed: {value}</p> </div> ); } export default App;
Output
Example − Toggle Button App
In this app, we will have a button to toggle between online and offline status. The current online status is logged using React.useLayoutEffect, and a message is displayed accordingly. So the code for this app is as follows −
import React from "react"; function App() { const [isOnline, setOnline] = React.useState(true); React.useLayoutEffect(() => { console.log("Online status: ", isOnline ? "Online" : "Offline"); }, [isOnline]); return ( <div> <h2>{isOnline ? "You are online" : "You are offline"}</h2> <button onClick={() => setOnline(!isOnline)}> Toggle Online Status </button> </div> ); } export default App;
Output
Example − Counter App
So let's see a simple counter application with the help of useLayoutEffect that increments the count on a button click and prints the value using the effect hook in the console.
import React from "react"; function App() { const [count, setCount] = React.useState(0); // Initialize with a number React.useLayoutEffect(() => { console.log(count); }, [count]); return ( <div> <h1>The count is {count} </h1> <button onClick={() => setCount(count + 1)}>Click here</button> </div> ); } export default App;
Output
This code is a React component that tracks the value of the count state whenever it changes with the useLayoutEffect hook. It shows the current count on the web page and allows the user to increase it by clicking a button.
Limitations
The useLayoutEffect hook can only be used at the top level of our component or within other custom hooks. It cannot be used within loops or conditions. Create a separate component and place the effect there if we need to use it in a loop or condition.
When we use React's Strict Mode in development mode, React performs additional checks to ensure that our cleaning code matches our setup code. If we run into problems as a result of this, make sure our cleaning code properly undoes what our setup code did.
If any of the items on which our effect depends are objects or functions produced within our component, the effect can execute more frequently than necessary. To fix this we can remove unnecessary object and function dependencies.
To Continue Learning Please Login
Login with Google