What are the alternatives for high order component in react? - reactjs

Coming with php background not sure how to implement a design with reusable code,
the problem:
we are creating a react/redux app with a lot of similar components that share a lot of functionality... I've read about HOC but was wondering if there are another solutions that would help in this situation!?

Component inheritance.
You can extend one component from some ComponentBase to share some functionality between them. But actually its different way from creating HOC. Hoc just allows you to pass some props to child, inheritance give you an ability to share methods and state.

There is something called function as child components (not sure if that's an official name but anyways)
The basic idea is that react accepts functions as child components, so for example instead of the react redux's connect HOC component you could do something like this
<Connect mapStateToProps={myMapper}>
{({ users, isLoading })} => {
//renders the user
}}
and the connect implementation is quite simple compared to a HOC.
render() {
return this.props.children(
this.props.mapStateToProps(this.state)
)
}
You can check a pretty interesting video about it here: https://www.youtube.com/watch?v=BcVAq3YFiuc

Related

Is it considered a bad practice to nest container component inside a presentational component? [duplicate]

I am new to react and redux. I have a scenario where there are nested components like this.
A > B > C > D
There is a property used in A component and it will be used in D component. So, I have two approaches:
Get state from redux store in component A and then pass it along as props to all it's child components even though it will be used only in D component.
I should connect to redux store in component D and fetch that property from there.
What is the correct approach?
As Dan Abramov, author of redux says in this issue
Both approaches of passing props down to children or connecting them
to the store are appropriate, however having nested connect()
components is actually going to give you more performance. The
downside is they're slightly more coupled to the application and
slightly harder to test, but that may not be a big issue.
He has also articulated a nice rule of thumb to follow on reddit
I do it this way:
Start by using one container and several presentational components
As presentational component tree grows, “middle” components start to pass too many props down
At this point, I wrap some leaf components into containers so that “middle” components don’t need to accept and pass down props that are
completely unrelated to them
Repeat
He has even tweeted regarding this:
Try to keep your presentation components separate. Create container
components by connecting them when it’s convenient.Whenever you feel like you’re duplicating code in parent components to provide data for same kinds of children, time to extract a container.
So in simple words:
You can use connect() at any level. Doing so makes the component smart, since it knows where its props come from. A dumb component just has props, and they could come from anywhere. A smart component is coupled to redux; a dumb component is not.
UPDATE: react-redux v7 and above
The same concept applies to useSelectors too. You can receive data in a container component and pass on to your presentational components, if multiple of its children make use of the same data
If however the data used by the children is different, you can choose to use useSelector individually within the child component. This will make sure that only those components re-render which actually need to
I would suggest if you are already using redux in your app then set the property in the redux store and fetch it in the component D.
But if the work flow is really simple and all the data is fetched from a single source per view, you can avoid redux as it is for complex state management.

React - Where is the best place to fetch data?

It is a conceptual question about a better way of fetching data using react and react with redux.
I have a component called UsersSelect which is a select component that displays the user information. Currently I'm fetching the user data inside this component to make it more reusable.
I also have an UsersTable component which does kind of the same as UsersSelect and, sometimes, I have them both rendered on the same screen which causes two identical fetches. To avoid this, I'm using redux-saga with takeLatest.
So my questions are:
Is it ok to use this?
Should I put the fetch logic on the parent component? Like an UsersPage component?
Is there another better option to simplify this?
I agree with Miro J.'s comment.
Since you're using the same data into two different components, it'd be better to fetch the data in the parent and pass it down as props to the children.
In your case, (it seems) both your components are very closely related.
In cases in which the components are not so close, but you'd still need the data, you could also load the data when setting up the root App component.
For react architecture, without redux , fetch data is working in parent, and yes UsersPage component should has data for the child components for work, but with redux you has some options, like to create a presentational components , or implement a factory pattern but this requiere that backend architecture couple
const factoryComponent = (FactoryComponent, DefaultComponent, props) => ({
Component: FactoryComponent || props.component || DefaultComponent,
props: { ...props, component: FactoryComponent ? props.component : fetch(url).then(data=>console.log(data)); },
})

Whats the need of mapDispatchToProps in a react-redux application?

Reading many articles and blogposts on this I understand(simplified)
mapDispatchToProps()(
clickHandler: ()=>dispatch(Action)
);
<Component onClick={this.props.clickHandler} />
Does the same as
<Component onClick={store.dispatch(action)} />
Which looks simpler than having all the hassle of using mapDispatchtoProps
I am new to redux and react in general and can't wrap my head around this. Is there an actual necessity to use it or is it just good coding practice?
There isn't an absolute necessity to use mapDisplayToProps but it will get pretty handy if your application grows.
In your second example you access the store object directly. This is not considered a good coding style because you couple your component to a global object which makes it harder to test the component in isolation or to use it in another context.
Think about each component as an isolated piece of software with the props passed to the component being the only interface to the rest of your application. This won't matter much for small example-like applications but pays off in real-world conditions.
The main idea of connect with mapDispatchToProps and mapStateToProps is to keep you UI components simple and easily reusable. Imagine, if you have 3 applications which have completely different architecture(redux, flux, pure React ContextAPI), but should reuse same UI components. If you incapsulate business logic directly to your components (2. example), then it might be very hard or even impossible to reuse it, because it is attached to some store (in the place where you use your <Component ... />).
Just as a side note and good example, how mapDispatchToProps can make your application clean is clear separation between business logic and UI component.
Example:
You have a Button component, which is used all over the application. Then you get a requirement that you need to have a logout button in different places of your application. One way would be to create a new regular React component, which will use the Button component inside and also have some logic.
connect with mapDispatchToProps comes to help you and allow to easily create a new LogoutButton component with attached logic (which also allows you to update the redux state), then whenever you need to have a logout button you simply use LogoutButton and there will be no need in any extra logic because it's all defined inside mapDispatchToProps and is already attached to the Button component.
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause a change of application state)

If given the choice, should I be passing data by passing through params or by connecting through the Redux store?

I'm using React and Redux and it's my first project in React overall. As of now I have a bunch of Components that all "get" and "set" the global data through Redux. So basically every component has this :
this.props.actions.UseInfo(this.props.commonData);
function mapStateToProps(state) {
return {
commonData: state.something.commonData
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(someActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ComponentName)
Now I noticed in React without Redux.. you have to structure your app to pass your data through parameters like
<SomeComponent someParam={this.commonData} />
<SomeComponent someParam={this.commonData} />
Is there any reason I should take the time to restructure my app to pass more information through parameters and use the Redux actions/reducers less unless if needed?
It seems like structuring to combine the best of both worlds .. maybe having the main components connect to the store and then pass that information down to it's sub components is probably the most ideal, but is there any reason why i "should" be doing that over just connecting everything through the store?
At the end of the day I feel like it's accomplishing the same thing.
Thanks for any input
Have a look at this article by Dan Abramov, the creator of Redux.
It says, basically, that container components get data via connect, and presentational components get data via props.
There are a couple of advantages to splitting out presentational or "dumb" components that simply react to their props. Namely, reusability and centralization (you know where to look for things, dumb components rarely require much maintenance).
In the real world it's never black and white, of course. Do the best you can but don't obsess over it, just do what makes sense for your app. Without knowing more about the hierarchy of your project, it's hard to know if you have a problem or maybe just a simple app and it doesn't make much difference. In general I would say watch out for nested "smart" components.

React: how to connect reusable components with usual dumb components

When I develop a React-based web-app, I often separate components into smart and dumb and also into reusable and custom.
Reusable components can be self-sufficient, such as e.g. <RedButton> or <CustomSelect> but they can also be middleware components, such as <FluxStoreBinder>. A middleware component renders its children while adding some functionality to them, usually such as subscribing-reading to/from a Flux store, or wrapping into some other stateful thing. However, some extra work is needed to connect a reusable smart middleware component to a dumb component because their props won't likely match. E.g. a <FluxStoreReader> may "return" a property named data, while a child of type <ToDoList> expects toDoItems.
The question which I want to ask is how to tell a middleware component which content to render in which way. What is the proper and recommended approach? Currently I've seen 3 ways of telling a middleware component how to render its children:
By providing a function through props, such as render={({arg1}) => <Child prop1={arg1}/>}. The features are: you can access own state/props/etc within this function; you can process and re-map props; you can specify which child to render depending on a condition; you can set needed props to the child without having to proxy through the middleware component.
By returning React.cloneElement(children, props) while providing a function to remap props.
By rendering React.cloneElement(children, props) and proxying received props down to the child. Pure component approach, no callbacks. This one don't have the features/flexibility of the above 2, and also requires some extra work: you need another middleware between your middleware and its child to re-map the props.
The fourth option suggested by Mike Tronic is to use higher-order components, which are basically component factories, where one of the required arguments is a child component class. It's almost the same as #3 - but you can't even change the type of the child once you've run the factory.
Which approach did you choose for your application? Why? Please share thoughts.
Would be great to hear a React guys' opinion.
check https://www.youtube.com/watch?v=ymJOm5jY1tQ
http://rea.tech/reactjs-real-world-examples-of-higher-order-components/ and
http://www.darul.io/post/2016-01-05_react-higher-order-components
What are Higher Order Components?
A Higher Order Component is just a React Component that wraps another one.
This pattern is usually implemented as a function, which is basically a class factory (yes, a class factory!), that has the following signature in haskell inspired pseudocode
hocFactory:: W: React.Component => E: React.Component
Where W (WrappedComponent) is the React.Component being wrapped and E (Enhanced Component) is the new, HOC, React.Component being returned.
The “wraps” part of the definition is intentionally vague because it can mean one of two things:
Props Proxy: The HOC manipulates the props being passed to the WrappedComponent W,
Inheritance Inversion: The HOC extends the WrappedComponent W.
We will explore this two patterns in more detail.
What can I do with HOCs?
At a high level HOC enables you to:
Code reuse, logic and bootstrap abstraction
Render Highjacking
State abstraction and manipulation
Props manipulation
We will see this items in more detail soon but first, we are going to study the ways of implementing HOCs because the implementation allows and restricts what you can actually do with an HOC.

Resources