Search code examples
reactjsstaterenderassign

How to persist counter value when the state changes?


In this component when I change the state, it reassigns counter=1 which I do not want. I just want that it assigns counter=1 only once and then does not assign it again during re-render.

And, I do not want to use useState for counter to solve this issue.


function App() {
    const [value, setValue] = useState(100);
    let counter = 1;
    return (
    <div>
    <button
        onClick={() => {
        setValue(value - 1);
        counter++;
        }}
    >
        click me
    </button>
    </div>
);
}

export default App;

Solution

  • You can use useRef:

    useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

    useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render.

    function App() {
      const [value, setValue] = useState(100)
      const counter = useRef(1)
      return (
        <div>
          <button
            onClick={() => {
              setValue(value - 1)
              counter.current++
            }}
          >
            click me
          </button>
        </div>
      )
    }