- 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 - flushSync() Method
FlushSync is a React function that allows us to force synchronous updates to the Document Object Model (DOM). In other words, it allows us to ensure that changes to our React components are quickly reflected on the web page. This function helps in updating the component state and the DOM in a synchronous manner.
In simpler terms, when we use flushSync(), React ensures that any changes to the component state are reflected in the DOM right away. This can be useful in certain situations where we want to make sure that the component's state and the DOM are in sync without any delay.
Syntax
flushSync(callback)
Small Example
import { flushSync } from 'react-dom'; flushSync(() => { setHereg(657); });
Parameters
callback − It is a function. React will quickly call this callback and synchronously flush any updates it has. It can also flush any remaining updates, Effects, or updates inside the Effects. If an update fails as a result of this flushSync call, the fallbacks can be returned again.
Return Value
flushSync returns undefined.
Examples
Example − Counter App
In this example we will have a simple counter app that increments the count value when a button is clicked. The flushSync() function is used after updating the counter state to ensure an immediate update in the DOM, keeping the displayed counter value synchronized with the component state without any delay.
import React, { useState, flushSync } from 'react'; const CounterApp = () => { const [count, setCount] = useState(0); const handleIncrement = () => { setCount(count + 1); flushSync(); // immediate update }; return ( <div> <h1>Counter: {count}</h1> <button onClick={handleIncrement}>Increment</button> </div> ); }; export default CounterApp;
Output
Example − Controlled Input App
This app will have a controlled input field in which the displayed text dynamically updates as the user types. The flushSync() function is used after updating the input value state, to make sure that there is an immediate update in the DOM. This helps maintain synchronization between the input field and the displayed text without any noticeable delay.
import React, { useState, flushSync } from 'react'; const InputApp = () => { const [inputValue, setInputValue] = useState(''); const handleChange = (e) => { setInputValue(e.target.value); flushSync(); // immediate update }; return ( <div> <label>Type something:</label> <input type="text" value={inputValue} onChange={handleChange} /> <p>You typed: {inputValue}</p> </div> ); }; export default InputApp;
Output
Example − Real Time Chat App
So we will create a simple app which uses flushSync. In this example, we will use a real-time chat application that updates a message indicator when new messages arrive. Here is the code for this chat app −
import React, { useState, useEffect } from 'react'; import { flushSync } from 'react-dom'; export default function ChatApp() { const [newMessages, setNewMessages] = useState(0); useEffect(() => { function simulateIncomingMessage() { flushSync(() => { setNewMessages(newMessages + 1); }); } const messageInterval = setInterval(simulateIncomingMessage, 5000); return () => { clearInterval(messageInterval); }; }, [newMessages]); return ( <div> <h1>Real-time Chat App</h1> <p>New Messages: {newMessages}</p> <button onClick={() => setNewMessages(0)}>Clear Messages</button> </div> ); }
Output
In this example code, the ChatApp creates fresh messages arriving at regular intervals. We have used flushSync to ensure that the message count is updated quickly when new messages arrive. To reset the message count to zero, click the "Clear Messages" button.
Limitations
flushSync might have a negative impact on performance. Use with caution.
Flushing pending Suspense borders can cause them to display their fallback state.
Before returning, flushSync can run any outstanding effects and synchronously apply any updates they contain.
flushSync can flush updates outside the callback if necessary in order to flush updates inside the callback. If there are waiting updates from a click, for example, React can flush those before flushing the updates inside the callback.
Summary
FlushSync is a React method that allows us to apply synchronous updates to the DOM. While it can be useful in some cases, it is generally recommended to use it only as last option due to the possible performance effect.
To Continue Learning Please Login
Login with Google