DEV Community

김재원
김재원

Posted on

I created react hooks for reducing re-rendering caused of statement change.

In React, a component will be re-rendered when state is changed.
What will be happened if the state is changed very frequently?
The component will be re-rendered frequently. It will affect to performance.

use-flush will help component to be re-rendered just once in n seconds.

Now, Let's take a look how it works and how to use it.

Explanation

Let's assume that the state will be changed very frequently like below.

  • + means every n seconds.
  • * means state is changed.
+--------+--------+--------+--------
  * *   *  ** *** *  *    *

The flushed state will be changed in every n seconds like below.

+--------+--------+--------+--------
         *(3)     *(6)     *(2)

Installation

$ npm i -S use-flush

Usage

If you click 5 times in 2 seconds, flushedCount will be [0, 1, 2, 3, 4].

import React, { useState } from 'react';
import { render } from 'react-dom';
import useFlush from 'use-flush';

const appRoot = document.getElementById('app');

const App = () => {
  const [count, setCount] = useState(0);
  const flushedCount = useFlush(count, 2000);

  return (
    <>
      <p>
        FLUSHED COUNT : {flushedCount.join(', ')}
      </p>
      <button onClick={() => { setCount(count + 1); }}>
        CLICK!
      </button>
    </>
  );
};

render(
  <App />,
  appRoot
);

You can check it on this repository.
Any PRs are welcome. :)

Top comments (1)

Collapse
 
dance2die profile image
Sung M. Kim

Would it be wrong to think useFlush as a debounce for a state?