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

counter increment

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

type something

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

real time chatapp

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.

reactjs_reference_api.htm
Advertisements