Preserving & Resetting State upon re-render
React stores the state for components, not the component itself.
This means that when react re-renders the page, the state is preserved.
React knows when to assign state to certain components based on their position.
When the position of that component changes or if the component is no-longer there for a given render, the state is removed.
Thus if the position of that component changes, because say you swap out a parent or if you hide that component to later to re-render it; then the state will be lost.
Keys
Sometimes you will want to reset the state of a component, but you will not want to hide it or change its position.
For this keys are used. They do not preserve the state, they simply say that this component has changed, and that the state should now be reset.
Here the key will change when to changes; thus resetting the state.
export default function Messenger() {
const [to, setTo] = useState(contacts[0]);
return (
<div>
<ContactList
contacts={contacts}
selectedContact={to}
onSelect={contact => setTo(contact)}
/>
<Chat key={to.id} contact={to} />
</div>
)
}
How do I preserve state
- Uplift the state from the component that is being reset
- Use CSS to hide the component
- If you need to preserve it for a while you can also use
localStorage