skip to Main Content

It isn’t really a problem but I’m seeking some new understanding in React.useState(). The program below runs as expected however I am not sure if it’s the correct way for performing my task.
Task is to use React.useState(0) to add and subtract and display the changes in the web browser.

function App(){
    const [myValue , setmyValue] = React.useState(0);
    function addValue(value){
        value = value + 1;
                return value;
    }
    function subValue(value){
        value = value - 1;
                 return value;
    }
    function handleAdd(){
        //setmyValue( myValue + 1);
                setmyValue(addValue(myValue))
    }
    function handleSub(){
        setmyValue(myValue - 1);
    }
    return (
        <div>
            <button onClick={handleAdd}>+</button>
            <p>{myValue}</p>
            <button onClick={handleSub}>-</button>
        </div>
    )
}
ReactDOM.render(<App/>, document.getElementById("part1"));

Any advice if passing the value myValue directly to thesetValue() function is correct or passing another function is the correct way.

2

Answers


  1. The way you’re using useState is fine but you can simplify this code quite a lot as per below:

    function App(){
        const [myValue , setmyValue] = React.useState(0);
        
        return (
            <div>
                <button onClick={() => setmyValue(myValue++)}>+</button>
                <p>{myValue}</p>
                <button onClick={() => setmyValue(myValue--)}>-</button>
            </div>
        )
    }
    ReactDOM.render(<App/>, document.getElementById("part1"));
    
    

    In answer to your question as a whole throug, for simple flows pass the value but if you need to do complex functions use a function.

    Login or Signup to reply.
  2. Você está usando correto, mas acho que poderia simplificar mais, desse modo.

    import React, { useState } from 'react';
    
    const App = () => {
      const [myValue, setMyValue] = useState(0);
    
      const handleAdd = () => {
        setMyValue(prevValue => prevValue + 1);
      };
    
      const handleSub = () => {
        setMyValue(prevValue => prevValue - 1);
      };
    
      return (
        <div>
          <p>{myValue}</p>
          <button onClick={handleAdd}>+</button>
          <button onClick={handleSub}>-</button>
        </div>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search