0

I've created a small example to show my problem.

import React, { useRef, useState } from "react";

export default function App() {
  const renderCount = ++useRef(0).current;
  const [, setValue] = useState(1);

  console.log("Render count", renderCount);

  const reRender = () => {
    setValue((prev) => prev + 1);
  };

  return <button onClick={reRender}>Render</button>;
}

Show in CodeSandbox

When I click the button 3 times the console output looks like this:

Render count  1
Render count  2
Render count  4
Render count  6

I would've expected the following:

Render count  1
Render count  2
Render count  3

Why doesn't it display each render count if it renders 6 times? And why does it render 6 times instead of 3 times?

Nepo Znat
  • 3,000
  • 5
  • 28
  • 49
  • Please make your runnable examples **here, on-site** using Stack Snippets (the `[<>]` toolbar button). Stack Snippets support React, including JSX; [here's how to do one](http://meta.stackoverflow.com/questions/338537/). Three reasons: People shouldn't have to go off-site to help you; some sites are blocked for some users; and links rot, making the question and its answers useless to people in the future. – T.J. Crowder Nov 05 '20 at 13:33
  • ```import React, { useState } from "react"; export default function App() { const [age, updateAge] = useState(0); console.log("Render count", age); const reRender = () => { updateAge((prev) => prev + 1); }; return ; } ``` – maheshwaghmare Nov 05 '20 at 13:38
  • I'm not sure why you have used `useRef`. Above is simple example to make it work. – maheshwaghmare Nov 05 '20 at 13:39
  • @maheshwaghmare - The OP's trying to track render counts, not state changes. – T.J. Crowder Nov 05 '20 at 13:41
  • Oh! My bad. Thanks for letting me know. I was not aware about it. – maheshwaghmare Nov 05 '20 at 13:51

0 Answers0