Logan Lee
Logan Lee

Reputation: 987

Updating just part of state and keeping others same when using useState hook

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

Answers (1)

Patrick Roberts
Patrick Roberts

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

Related Questions