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.