Skip to content

Instantly share code, notes, and snippets.

@artalar
Created September 8, 2018 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artalar/6927068463ae0b8ff2d34fdd88b04188 to your computer and use it in GitHub Desktop.
Save artalar/6927068463ae0b8ff2d34fdd88b04188 to your computer and use it in GitHub Desktop.
Detailed explanation of the new React context
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