React Logic HOC
Idea
- Write dumb components based on props only
- Consume hook from context
- Get new props with some logic from hook
- Now dumb components is smart components
Getting Started
Create component
import React from 'react';
import withLogic from 'react-logic-hoc';
export const ComponentContext = React.createContext();
export const Component = (props) => {
};
const WithLogicComponent = withLogic(ComponentContext)(Component);
export default WithLogicComponent;
Provide logic
const useComponentLogic = (props) => {
return propsWithLogic;
};
<ComponentContext.Provider value={useComponentLogic}>
<WithLogicComponent />
</ComponentContext.Provider>
Advanced
Use composeProviders for reduce complexity
import React from 'react';
import { composeProviders } from 'react-logic-hoc';
const LogicProvider = composeProviders(
[HeaderContext, useHeaderLogic],
[SidebarContext, useSidebarLogic],
[ContentContext, useContentLogic]
);
const Page = () => (
<LogicProvider>
<Main />
</LogicProvider>
);
API
withLogic
takes one argument Context
and return HOC
composeProviders
takes arguments [Context, value]
and return component that render children