skip to Main Content

Making a simple counter-example. What am I doing wrong here?

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

export default function Ex2() {

    const [counter, setCounter ] = useState(0);

    const increaseValue = () => {
        setCounter(counter++);
    }

    const decreaseValue = () => {
        setCounter(counter--);
    }

    return (
        <div className="ex2">
            <p>{counter}</p>
            <p><button onClick={increaseValue}>increase</button><button onClick={decreaseValue}>Decrease</button></p>
        </div>
    )
}

Error:

enter image description here

3

Answers


  1. setCounter(counter++); and setCounter(counter--); are actually changing the variable at the end of the line as well, not giving you counter + 1 and counter - 1, but it’s a constant, so that error is thrown

    Login or Signup to reply.
  2. counter++ is an operation that is the logical equivalent of counter = counter + 1. It’s attempting to modify the state value directly, which is prohibited in React.

    counter + 1 is an expression without assignment, so it’s evaluated as a new value when passed to your set function.

    That’s the real problem with your code. However, the actual compilation error is because by incrementing the state value you’re attempting to reassign a constant.

    Login or Signup to reply.
  3. In your code you are doing counter++ which is trying to increase the counter with post increment operator ++ variable.

    Remember to always use setter function to update your state.

    There are a few ways you can update your counter by doing : setCounter(counter+1)
    or use below callback approach

    Below is the better approach using setState callback.

    import React, { useState } from 'react';
    
    export function App(props) {
    
      const [counter, setCounter] = useState(0);
    
      const IncreaseValue = () => {
        setCounter((prev)=>++prev);
      }
    
      const DecreaseValue = () => {
        setCounter((prev)=>--prev);
      }
    
      return (
        <div className='App'>
          <h1>Hello React.</h1>
          <h2>Start editing to see some magic happen!</h2>
    
          <p>{counter}</p>
           <p><button onClick={IncreaseValue}>increase</button><button onClick={DecreaseValue}>Decrease</button></p>
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search