Skip to content

Instantly share code, notes, and snippets.

@Visible-Radio
Created December 4, 2022 21:01
Show Gist options
  • Save Visible-Radio/ca5821b517986ed22562aaedbc506269 to your computer and use it in GitHub Desktop.
Save Visible-Radio/ca5821b517986ed22562aaedbc506269 to your computer and use it in GitHub Desktop.
Re-initialize form component's internally managed state using key prop
import { useState } from "react";
export default function FormWithKey() {
const [childKey, setChildKey] = useState(1);
return (
<div style={{ display: "flex", gap: "0.5rem", flexDirection: "column" }}>
<button onClick={() => setChildKey(prev => prev * -1)}>
Reset child by changing child Key
</button>
ChildKey: {childKey}
<InputComponentWithOwnState initState="init state" key={childKey} />
</div>
);
}
function InputComponentWithOwnState({ initState }: { initState: string }) {
const [state, setState] = useState(initState);
return (
<div
style={{
outline: "1px solid pink",
display: "flex",
flexFlow: "row wrap",
justifyContent: "center",
padding: "1rem",
borderRadius: "0.25rem",
}}
>
<p style={{ width: "100%", textAlign: "left" }}>
This form component maintains it's own state internally. It is
intialized with an initState prop passed from the parent.
</p>
<p style={{ width: "100%", textAlign: "left" }}>
Init state values passed to useReducer / useState only affect the state
value returned from the hook on component mount.
</p>
<p style={{ width: "100%", textAlign: "left" }}>
<em>Unless...</em>
</p>
<p style={{ width: "100%", textAlign: "left" }}>
You change the <em>key</em> applied to the component as well.
</p>
<p style={{ width: "100%", textAlign: "left" }}>
This could allow us to remove data fetching logic entirely from forms
that need to be initialized with preset values from the server.
</p>
<label
style={{
padding: "2rem",
display: "flex",
gap: "0.5rem",
}}
>
Some From Value
<input onChange={e => setState(e.target.value)} value={state} />
</label>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment