DEV Community

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

Posted on

ReactJS Hook Pattern ~Abandon Render Pattern~

・ReactJs officially recommends the abandon render pattern. This pattern tracks previous values instead of using the usePrevious hook. Although ReactJS does not allow you to execute the setter function of the state during rendering(This causes an infinite loop), this pattern enables you to do so within an if check. The component then abandons the current rendering and restarts a 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>
      <h1>Abandon Render Pattern</h1>

      <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)