This pattern allows you to access the latest value of a prop, state, or a callback without needing to list it in the dependency array. It's an intentional replicate of an old default feature of class-based React (which may cause typical asynchronous bugs in some cases, e.g: Imagine, you start the async thing, then props change while that is in flight, when your code continues you'll have the latest values of this.props rather than what you want: the values that existed at the time the function started running adheres to its closure):
functionuseExampleOne(callback){React.useEffect(()=>{callback()},[callback])// <-- have to include the callback in the dep array}functionuseExampleTwo(callback){const{current: latestCallbackRef}=React.useRef(callback)React.useLayoutEffect(()=>{// https://kentcdodds.com/blog/useeffect-vs-uselayouteffect#one-special-caselatestCallbackRef=callback})React.useEffect(()=>{latestCallbackRef()},[])// <-- don't have to include the callback in the dep array}
Context Module Functions
SoC and enhancing reusability, more details at 02:20.
Using useRef (at useToggledefinition) to secure initialState.
Returning objects of props (in the form of returned value from a function) in your custom hook/component so that later you can simply spread across the rendered UI, i.e. composing props. See more at 01:50 and at the returned onClick function in getTogglerProps from Extra Credit.