I’ve been working on a React project and I’m having some trouble deciding between using useState and useReducer for state management in a complex component. Here’s a brief overview of my component structure:
• The component handles user inputs from a form.
• It performs various calculations based on the inputs.
• There are multiple state variables that need to be updated based on user actions.
Currently, I’m using useState for managing state, but the code is becoming quite messy with multiple useState calls and complex state updates. Here’s a simplified version of what I have:
const [name, setName] = useState('');
const [age, setAge] = useState('');
const [results, setResults] = useState([]);
const handleInputChange = (e) => {
const { name, value } = e.target;
if (name === 'name') {
setName(value);
} else if (name === 'age') {
setAge(value);
}
};
const handleCalculate = () => {
// Perform calculations and update results
setResults([...results, /* new result */]);
};
return (
<form>
<input name="name" value={name} onChange={handleInputChange} />
<input name="age" value={age} onChange={handleInputChange} />
<button type="button" onClick={handleCalculate}>Calculate</button>
</form>
<div>
{results.map((result, index) => (
<p key={index}>{result}</p>
))}
</div>
);
I’ve read that useReducer can be a better alternative for managing complex state logic. Could someone explain the pros and cons of useState vs useReducer and maybe provide an example of how I could refactor my component using useReducer?
Thanks for your help!