DEV Community

Cover image for ReactJS Hook Pattern ~Abandon Rendering~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Hook Pattern ~Abandon Rendering~

・This pattern is officially recommended in ReactJS. It tracks the previous value instead of using the usePrevious hook. During rendering, you can use an if statement to check whether the current value differs from the previous one. If the current value is the same as the previous one, updating the state mid-rendering causes React to abandon the current rendering and start again with the new one.

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  const [prevCount, setPrevCount] = useState(count);

  if (count !== prevCount) {
    setPrevCount(count);
  }

  return (
    <div>
      <p>Current count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)