Created
September 8, 2018 18:23
-
-
Save artalar/6927068463ae0b8ff2d34fdd88b04188 to your computer and use it in GitHub Desktop.
Detailed explanation of the new React context
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
export const connect = selector => target => ({ children, ...props }) => { | |
let updateFromParent = true; | |
let cachedState = null; | |
let cachedComponent = null; | |
return ( | |
<Consumer> | |
{context => { | |
const state = selector(context, props); | |
if (!updateFromParent && (state === cachedState || shallowCompare(state, cachedState))) { | |
updateFromParent = false; | |
return cachedComponent; | |
} else { | |
updateFromParent = false; | |
cachedState = state; | |
return (cachedComponent = React.createElement(target, { ...props, ...state }, children)); | |
} | |
}} | |
</Consumer> | |
); | |
}; | |
// example | |
// ComponentList.js | |
export const ComponentList = connect(context => ({ list: context.list }))(ComponentList_raw); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment