Is It Necessary To Use The Spread Operator In Usereducer?
EDIT: after checking Brian's answer, I found out that even in the 2nd example, removing ...state would cause the same behaviour as the 1st example, so this question was wrong to as
Solution 1:
I understand that this is a very similar question to this one, but I'm giving an answer anyway to hopefully prevent future readers from getting incorrect information.
Neither useState
nor useReducer
do any merge of previous values whatsoever. Any retention of previous state values is your responsibility during the state update (either in the setState
call, or in the reducer function definition).
You can see this plainly in the modified code below. All I have changed is removing the ...state
from each switch case.
const {useReducer} = React;
const initialState = {
name: 'Tom',
age: 30
}
constreducer = (state, action) => {
switch (action.type) {
case'name':
return {
name: 'John'
}
case'age':
return {
age: 25
}
default:
return state
}
}
constExample = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div><p>Name: {state.name}</p><p>Age: {state.age}</p><buttononClick={() => dispatch({ type: 'name' })}>Click to update name</button><buttononClick={() => dispatch({ type: 'age' })}>Click to update age</button></div>
)
};
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><divid="react"></div>
The reason the spread operator is used so frequently for this purpose is it's the least tedious method for putting all unchanged values into the new object.
Post a Comment for "Is It Necessary To Use The Spread Operator In Usereducer?"