If I have a component:
function MyComponent() {
const state = useState(resetState())
return jsx(state)
}
then I can trigger a state reset by passing a key to MyComponent:
<div>
<MyComponent key={'resetStateOnChangingThisString'} />
</div>
If I want to refactor this component into a hook, what is the hooks equivalent of triggering a reset exactly when the key changes?
- not using
useEffectsince it should reset before rendering - not using
useMemobecause that doesn't guarantee stability
I can use a combination of useMemo with a useRef to guarantee stability. Is this the best approach or am I missing something simpler?
This is the simplest approach I've found so far:
or a version without
useState: