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
The way you’re using useState is fine but you can simplify this code quite a lot as per below:
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.
Você está usando correto, mas acho que poderia simplificar mais, desse modo.