Skip to content

React 18 support

Hòa Võ edited this page Jun 10, 2024 · 3 revisions

Using reactive-store with React version 18

  • React 18 just release and add many new thing to the library, but the biggest change is an introduction of concurrent rendering. Generally, it allow UI render process is interruptable. See more detail here
  • For example you have a large list of product and a filter input field. Every time you type in a filter field, the UI response and update product list
import {Store,StoreInjector} from "@mcsheffey/reactive-store";

const generateProduct = () => {
  const result: Array<string> = [];
  for (let i = 0; i < 10000; i++) {
    result.push(`Product ${i}`);
  }
  return result;
};

const products = generateProduct()
const store = new Store()
store.create("query","");

const Component = ({ name }: any) => {

  const query = store.get("query");

  function handleQueryChange(e) {
      store.update("query", e.target.value); 
  }

  const filterProduct = products.filter(product => product.includes(query));
  return (
    <div>
        <h1>React 18</h1>
        <input onChange={handleQueryChange}></input>
        {filterProduct.map(res => (
          <p>{res}</p>
        ))}
    </div>
  );
};

const App = StoreInjector([store, secondStore], Component);

const rootElement = document.getElementById('root');
const root = ReactDOMClient.createRoot(rootElement as any);

root.render(<App />);

If you slowdown CPU to 4x you can see input field will be lagging and late response as we type or delete character. In React18 we cant reduce this by using the new API by React: startTransition or useTransition hook. Thanks to the implematation under the hood, reactive-store allow use using these new api easily, alll you have to do is change update function to:

 function handleQueryChange(e) {
    React.startTransition(() => {
      store.update(keys.query, e.target.value);
    });
 }

or

 const [isPending, startTransition] = React.useTransition();
 function handleQueryChange(e) {
    startTransition(() => {
      store.update(keys.query, e.target.value);
    });
 }

You can see it will be reduce the lagging of filter field See full code example here

Clone this wiki locally