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.
Related posts
- How to use ast-grep with GraphQL — posted 2024-09-24
- Next.js App Router (RSC) projects w/ open source code — posted 2024-07-30
- Next.js Relay GraphQL Pokemon example — posted 2024-05-22
- Example Node.js Passport.js SAML app using OneLogin — posted 2024-05-10
- Aphrodite to CSS Modules codemod — posted 2022-12-09
- Simple codemod example with jscodeshift — posted 2021-05-03