Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active March 1, 2023 06:22
Show Gist options
  • Save yano3nora/3f92f45f7241973b5dbb92d458f7f6b3 to your computer and use it in GitHub Desktop.
Save yano3nora/3f92f45f7241973b5dbb92d458f7f6b3 to your computer and use it in GitHub Desktop.
[js: React Re-Mount by Key Prop] #js
/**
* @link
* https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key
* https://qiita.com/putan/items/8d976afab638ffb96acb
* https://stackoverflow.com/questions/35792275/how-to-force-remounting-on-react-components
*/
// 例えばこんな email 編集 component があったとする
export const EmailInput = ({ initial }: {
initial: string
}) => {
const [input, setInput] = React.useState(initial)
return <input
onChange={e => setInput(e.target.value)}
value={input}
/>
}
// user を fetch して email 編集 component を出すような場面
export const App = () => {
const { data } = useQuery(/* fetch from api */)
return <EmailInput
initial={data.user.email}
{
/**
* react は key prop で component を識別する
* key prop を変更した場合 re-render ではなく
* 別 component として改めて mount される
*
* これを利用し user.id 変化など任意タイミングで
* 「内部の state 含め mount し直す (=リセット)」 を実現できる
*/
}
key={data.user.id}
/>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment