Reputation: 987
Hello can I do the following to update just a portion of state and keep others same?
const stuff ={ 'a':'alpha', 'b':'alpha' };
const [letter,setLetter]=useState(stuff);
// update
// can i do it this way?
setLetter(...letter,'a':'omega');
// will this result in:
// letter==={'a':'omega', 'b':'alpha'}
Upvotes: 1
Views: 503
Reputation: 51876
Here's a custom hook I like to use for this situation. I call it useLegacyState()
since this mimics the behavior that the older class component states have:
const useLegacyState = initialState => useReducer(
(state, update) => ({ ...state, ...update }),
initialState
);
// usage
const [letter, setLetter] = useLegacyState(stuff);
// update
setLetter({ a: 'omega' });
// will result in: { a: 'omega', b: 'alpha' }
Upvotes: 3