Partial update

2 snippets across 2 stacks - React, TypeScript

REReact

Objects in State

RE · useState
Syntax
setState(prev => ({ ...prev, key: newValue }));
Example
function ProfileEditor() {
  const [profile, setProfile] = useState({
    firstName: '',
    lastName: '',
    bio: '',
  });

  function handleChange(field, value) {
    setProfile(prev => ({
      ...prev,
      [field]: value,
    }));
  }

  return (
    <>
      <input
        value={profile.firstName}
        onChange={e => handleChange('firstName', e.target.value)}
        placeholder="First name"
      />
      <input
        value={profile.lastName}
        onChange={e => handleChange('lastName', e.target.value)}
        placeholder="Last name"
      />
    </>
  );
}

Note Always spread the previous object to create a new copy. Directly mutating state (profile.firstName = 'X') will NOT trigger a re-render because React compares by reference.

TSTypeScript

Partial<T>

TS · Utility Types
Syntax
type Result = Partial<OriginalType>;
Example
interface Settings {
  theme: "light" | "dark";
  fontSize: number;
  notifications: boolean;
}

function updateSettings(current: Settings, changes: Partial<Settings>): Settings {
  return { ...current, ...changes };
}

const updated = updateSettings(
  { theme: "light", fontSize: 14, notifications: true },
  { fontSize: 16 } // only need to pass what changed
);
Output
// Partial<Settings> makes all properties optional

Note Partial only operates one level deep. Nested objects keep their original required types. For deep partial, you need a custom recursive type or a library utility.

Frequently asked questions

How does React handle partial update?
This task is covered in 2 stacks on this page: React, TypeScript. The "Objects in State" snippet in React uses `setState(prev => ({ ...prev, key: newValue }));`.
Which code does the React example use?
The "Objects in State" snippet uses `setState(prev => ({ ...prev, key: newValue }));`, from the useState section of the React cheat sheet.
Which stacks cover "partial update" on this page?
React, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Objects in State": Always spread the previous object to create a new copy. Directly mutating state (profile.firstName = 'X') will NOT trigger a re-render because React compares by reference.