Created
September 11, 2019 20:31
Using This-Like Ref Structure to Solve Hook State Updating and Function Reference Problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { memo, useCallback } from 'react'; | |
import ChildComponent from './wherever/ChildComponent.js'; | |
const updateChild = (props, childId, changes) => { | |
props.onUpdate({ | |
type: 'childChanged', | |
childId: childId, | |
changes: changes, | |
}); | |
}; | |
function ThisLikeExample(props) { | |
const thisLike = React.useRef(); | |
thisLike.current = props; | |
// Do something with state changes using the "thisLike" ref reference to get the most up-to-date props | |
// Note the intentionally empty dependency arrays on these callbacks, meaning the function references will never change | |
// NEVER use props directly inside a callback for useCallback, useEffect, etc. | |
const onUpdateChild1 = useCallback((changes) => { | |
updateChild(thisLike.current, 'child1', changes); | |
}, []); | |
const onUpdateChild2 = useCallback((changes) => { | |
updateChild(thisLike.current, 'child2', changes); | |
}, []); | |
// Assuming ChildComponent is memo'd, will only re-render if their state prop reference changes, the function references never change | |
// This architecture benefits most from an immutable style so that all data equality can be determined by reference equality | |
return ( | |
<div> | |
<ChildComponent state={props.state.child1} onUpdate={onUpdateChild1} /> | |
<ChildComponent state={props.state.child2} onUpdate={onUpdateChild2} /> | |
</div> | |
); | |
} | |
export default memo(ThisLikeExample); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!
Your comment here was helpful to explain this:
(copying here in case useful to others)