Search code examples
reactjscounterincrement

ReactJS: Increment counter keeps refreshing component


So recently I started a project for fun to mess around with NextJS.

I ran into a problem regarding my count state:

//Core
import React, { useState, useEffect } from 'react';

//Style
import styles from './form.module.scss';

export default function Form({ placeholder }) {
  const [count, setCounter] = useState(0);

  return (
    <form>
      <input
        type='text'
        placeholder={placeholder}
        className={styles.error}
      ></input>
      <button onClick={() => setCounter(count + 1)}>{count}</button>
    </form>
  );
}

This keeps refreshing my count state everytime I click the increment button. What is the correct way to do a increment on click, without rerendering the comoponent?

I found examples like these online: https://codesandbox.io/s/react-hooks-counter-demo-kevxp?file=/src/index.js:460-465

How come my counter keeps resetting, and theirs is not?


Solution

  • You are inside a form.

    Use preventDefault first in order for the form not to be submitted everytime.

      <button
        onClick={(e) => {
          e.preventDefault();
          setCounter(count + 1);
        }}
      >
        {count}
      </button>
    

    See it in action here