SaltyCrane Blog — Notes on JavaScript and web development

How to remount a React component when a prop changes

To remount a component when a prop changes, use the React key attribute as described in this post on the React blog:

When a key changes, React will create a new component instance rather than update the current one.

The example below shows how the key attribute can be used. In Parent, the key attribute of <Child> is set to String(primaryExists). When primaryExists changes in the parent component, the child component unmounts and remounts allowing useState to re-initialize its state with the intial value passed in from props (!primaryExists). Play with it on CodeSandbox.

import React, { useState } from "react";

function Parent() {
  // Note: in my real code, primaryExists was derived from API data,
  // but I useState here to simplify the example
  const [primaryExists, setPrimaryExists] = useState(true);
  return (
    <div>
      <label>
        <input
          checked={primaryExists}
          onChange={() => setPrimaryExists(x => !x)}
          type="checkbox"
        />
        Primary exists
      </label>
      <Child key={String(primaryExists)} primaryExists={primaryExists} />
    </div>
  );
}

function Child({ primaryExists }) {
  const [isPrimary, setIsPrimary] = useState(!primaryExists);
  return (
    <div>
      <label>
        <input
          checked={isPrimary}
          onChange={() => setIsPrimary(x => !x)}
          type="checkbox"
        />
        Is primary
      </label>
    </div>
  );
} 

Additional information

Sebastian Markbåge, from the React core team, reinforced the usage of keys on single items:

...BUT it has given the misinterpretation that only lists need keys. You need keys on single items too. In a master/detail, the detail should have a key.

Comments