1

I have been created a new React application using create-react-app, and i make a test with render counter.

Consider the following code:

import React, { useState } from "react";

let render = 0;

export default function App() {
  const [counter, setCounter] = useState(0);
  render++;

  return (
    <div>
      <button
        onClick={() => setCounter(counter + 1)}
      >{`Clicked ${counter} times`}</button>
      <p>{`Render counter: ${render}`}</p>
    </div>
  );
}

At my logic the render variable at the first time need be start with 1, but... it's start with 2, and after i click on the button the render counter go to 4 not 3.

In my knowledge the render counter should change after each render when the state change, and state change 1 time per click, can someone explain me what's wrong? or why it's occours?

Sandbox: https://codesandbox.io/s/little-sky-squ82?file=/src/App.js

Thanks!

Gabriel Gomes
  • 139
  • 1
  • 3
  • 20
  • 1
    you have [``](https://reactjs.org/docs/strict-mode.html) enabled (in index.js) which will result in double renders in development, but not in production. Also, there is a render before you are even able to click the button. – pilchard Dec 28 '20 at 23:35
  • Does this answer your question? [What is StrictMode in react?](https://stackoverflow.com/questions/53183362/what-is-strictmode-in-react) – pilchard Dec 28 '20 at 23:40
  • thanks, now i understood! – Gabriel Gomes Dec 28 '20 at 23:55

1 Answers1

-1

It should work properly:

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

export default function App() {
  const [counter, setCounter] = useState(0);
  const render = useRef(1);

  useEffect(() => {
    render.current++;
  });

  return (
    <div>
      <button
        onClick={() => setCounter((prevCount) => prevCount + 1)}
      >{`Clicked ${counter} times`}</button>
      <p>{`Render counter: ${render.current}`}</p>
    </div>
  );
}

Try to useRef() to track render count and if you updating state that uses prev state don't to like this:setCounter(counter + 1). You should do like this: setCounter((prevCount) => prevCount + 1) because it might make problems.

Krystian
  • 69
  • 6