The best way to update and combine state in React's useState hook is by using the functional update pattern and spreading the previous state to maintain immutability.
Example (Updating & Combining State)
import { useState } from "react";
function App() {
const [state, setState] = useState({ name: "John", age: 25 });
const updateAge = () => {
setState(prevState => ({ ...prevState, age: prevState.age + 1 }));
};
return (
<div>
<p>{state.name} is {state.age} years old.</p>
<button onClick={updateAge}>Increase Age</button>
</div>
);
}
export default App;
The best way to update and combine state in React's useState hook is by using the functional update pattern and spreading the previous state to maintain immutability.
Example (Updating & Combining State)
import { useState } from "react";
function App() {
const [state, setState] = useState({ name: "John", age: 25 });
const updateAge = () => {
setState(prevState => ({ ...prevState, age: prevState.age + 1 }));
};
return (
<div>
<p>{state.name} is {state.age} years old.</p>
<button onClick={updateAge}>Increase Age</button>
</div>
);
}
export default App;