I have a question about how to structure a React/Redux app.
As far as I understand, it's not recommended practice to reference containers inside a component. However when nesting components withing a Redux app, the top level container is bound with a connect() and mapStateToProps etc, but it seems strange to pass in all props down the line to -only- components.
When structuring an app with a nested component for example like:
Dialog > Form > Tab > Input Section > Input control
the input control could have a prop isVisible, where it seems strange to me that I would have to pass the prop all the way down the tree.
So my question is mainly, is this indeed what is recommended and how is this handled? Is this for example simplified by setting props to something like:
{
inputProps: { visible: false }
}
?
Or, can I reference a container inside my component, so I can have a separate connect() for only the props actually relevant?
One of the main points of Redux is to allow individual components to connect to the store and extract the data they need. Also, don't overthink the whole "container/component" distinction in terms of separating things in the codebase.
See the Redux FAQ entry at https://redux.js.org/faq/react-redux#should-i-only-connect-my-top-component-or-can-i-connect-multiple-components-in-my-tree for more info on connecting multiple components, and Dan Abramov's tweet at https://twitter.com/dan_abramov/status/802569801906475008 for thoughts on "container vs presentational" structuring.
If you find yourself passing down many properties, maybe they should be containers.
Just take redux-form as an example. It could perfectly be all about components, but they decided to use redux as well.
Related
After a lot of search and working with React and React Native. I still have a pretty vague opinion on which
is best to use and in what situations
Having the parent component be connected to the store and passing as props all data to children functional components. This what I initial though was the "React" way but pretty soon I saw that as the app grow the amount of logic handled by this parent component starting too be to big and messy.Also child components start to have children of its own and so on and so forth.
Having parent component (Screen for example) that is functional and each child that needs information from the store will be connected to it. This is much more "clean" solution but will create a lot of store connection "duplications" which are not necessary.
Using Redux store
My question in general which is more recommended pattern to use and in which use cases, also would be nice to know what is the price for having a lot of connected (containers) components
Not sure i can provide a right or wrong answer for this question as each has its pros and cons.
My rule of thumb is to connect deeply nested components only when their parents are "proxies of props". That is they accepts props only to pass them down to their children.
If i may quote (myself) from this answer:
Avoid connecting components when you can and pass down the props to
the children, the main reason for this is to prevent dependency on
redux. I prefer keep my components "dumb" as i can and let them
concern only on how things should look. I do have some components that
concern on how things should work and these components are mainly
dealing with logic and passing down data to the children, they are the
components i often connect.
When i notice that my app is scaling and some of my components are
acting as a proxy of props (i even got a word for that! "Propxy"),
that is they get props from their parent and pass them down without
using them, i usually inject a connected component in the middle of
the components tree so i can let the "propxy" components down the tree
flow be more lighten and slim
You should also note that one more pitfall with connected components is that each render will trigger the mapstateToProps method. if you got some heavy logic there you should memoize it, usually done with reselect
As for the benefit of connecting a component, well you probably realize that already. you get quick access to the Provider's state via react's context.
Edit
As a followup to your comment:
about the rendering - wont I have much more unnecessary rendering if Ill have a deep nested children (common in medium to large apps) that will be unnecessarily re rendered on each parent update
Well the connect HOC wrapper won't trigger a re-render if the previous object of mapStateToProps is the same as the current object returned. so no unnecessary re-renders to your connected component will take place.
You can read in more details on how it works and how the logic was evolved over time in this article
I use the first option.
The cons you wrote are correct, but i think its easier to debug and understand the data flow this way.
Don't connect a component to redux if the current component doesn't use this data from redux and only passes.
If the component uses data then connect to redux.
If the current component uses data from redux and the next component also uses it then you can pass and don't need to connect the next component to redux.
MAIN RULE:
if there is a gap in the data usage chain from parent to child then don't need to pass data from parent to child
connect(parent) (don't use props) => child (don't use) => child (don't use) => child (using) - better to connect last child. Isuue related to props dreeling
I'm working on a React + Redux project with a couple of other developers and we can't agree on what the best practice is regarding where to pass in the state and the actions.
My approach is to have a 'container' or 'provider' component, which is the parent component, all required states and actions are mapped to state and passed down into child components, creating a single source of truth. However the down side to that is, you have to remember to pass actions and values down through each child component, which can be tricky to follow.
Another developers approach is to use the mapStateToProps on each component where it is needed, at any point in the stack. So if a child component three or four levels down requires a certain state, he would use mapStateToProps on that component. He would also import action creators directly using the import keyword, instead of calling them as props. I don't like this approach because you're potentially injecting states multiple times and you can't switch out your state or actions quickly in one place.
I can see both approaches have their merits and fallbacks, so I just wondered if there was a definite best practice as to where and when to inject state/actions into a stack of React components.
I worked on a relatively large Redux codebase and the approach we chose and which I like was your second approach using mapStateToProps on containers component which dispatch actions and delegate rendering to dumb components.
You want to be able to reuse them in many places without having to pass down a state. Your top redux state is still the source of truth but mapStateToProps will allow you to access only the part of the state which you need within this container.
Redux documentation is amazingly well done, check it out, it recommends container components implementing mapStateToProps http://redux.js.org/docs/basics/UsageWithReact.html
It's up to you how many components you connect to Redux, but generally speaking having more connected components is better for performance. For more information, see the Redux FAQ on connecting multiple components, as well as my blog post Practical Redux, Part 6: Connected Lists, Forms, and Performance.
I am trying to find out why do I need redux if RN already have state, I can use state as I want as action or change something.
So why would I need it?
Redux provides a "shared state" that every component can access. For example, you may have found that a parent component needs to be aware of the state of a child component. You can resolve this in React alone by passing down a method as props to the child but this isn't a pattern you want to be repeating again and again, especially as your component structure becomes more complex and hierarchical. Redux provides an elegant solution. For small apps though, it's probably not necessary.
When you create React components, do you mostly follow the philosophy of only having dump/presentational react components that are connected to Containers? Only having dump components fulfils one of the main principles of redux (single source of truth) but complicated things when it comes to component isolation. By that i mean that:
... i end up have a table component which can present data and have the ability to select rows, but selection don't work unless its connected to the store via a container. This is good in theory because a lot of other components rely on that selection so having everything going through the store keeps everything in sync. However, it means that the table component cannot be fully interactable by itself (selection won't work if its not connected to the store). This could make automated UI tests slightly harder to test as each component will need to have a related container in order to work properly.
Another example; say that you have a dialog box, would you have the show state within the component itself or have it connected to the store through a container?
Any thoughts?
I personally like the Presentational and Container Components approach. It make the code clearer, cleaner and way more reusable.
The idea behind it is that your Presentational Component MUST NOT perform any action on the data, it is purely UI. And this data must come from your container (from the Redux Store, or from an helper class etc.)
The best practice is to pass down your Presentational Components functions from your Container Components via props.
// Container Component
handleChange(e) {
this.setState({ username : e })
}
render() {
return (
<Boarding
placeholder={this.state.placeholder}
error={this.state.error}
onChangeText={this.handleChange}
name={this.props.FB_user.user_firstname}
ProfilPicture={this.props.FB_user.user_picture} />
)
}
export default connect((state) => ({
FB_user: state.statusLogin,
}), {})(BoardingContainer)
Here is a simple example on how you can pass a function down your Presentational Component (which is TextInput here) and get connect to it to get back the data inputed in the TextInput.
Also, if you watch closely you'll see I pass this.props.FB_user.user_firstname && this.props.FB_user.user_picture that comes from the Redux Store that I connected to using the last lines of the code example.
Here is a very famous Medium article to get more details : https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.smfbi5hjj
Hope this helps, if you have any more questions, ask me.
So say you have a chat aplication with this component structure:
<ChatApp>
<CurrentUserInfo>...</CurrentUserInfo>
<ChatsPanel>...</ChatsPanel>
<SelectedChatPanel>
<MessagesList>
<MessageBaloon>
<MessageText></MessageText>
<MessageUserHead></MessageUserHead>
</MessageBaloon>
...
</MessagesList>
<SelectedChatPanel>
</ChatApp>
And a Redux state like:
{
currentUser: ...,
chatsList: ...,
selectedChatIndex: ...,
messagesList: [ ... ]
}
How would you make the current user information available to the <MessageUserHead> component (that will render the current user thumbnail for each message) without having to pass it along all the way from the root component thru all the intermediate components?
In the same way, how would you make information like current language, theme, etc available to every presentational/dumb component in the component tree without resorting to exposing the whole state object?
(UPDATE: Having spent some time on option 4, I personally think it's the way to go. I published a library, react-redux-controller built around this approach.)
There are a few approaches that I know of from getting data from your root component, down to your leaf components, through the branches in the middle.
Props chain
The Redux docs, in the context of using react-redux, suggest passing the data down the whole chain of branches via props. I don't favor this idea, because it couples all the intermediate branch components to whatever today's app structure is. On the bright side, your React code would be fairly pure, and only coupled to Redux itself at the top level.
Selectors in all components
Alternatively, you could use connect to make data from your Redux store available, irrespective of where you are in the component tree. This decouples your components from one another, but it couples everything to Redux. I would note that the principle author of Redux is not necessarily opposed to this approach. And it's probably more performant, as it prevents re-renders of intermediary components due to changes in props they don't actually care about.
React children
I haven't thought a great deal about doing things this way, but you could describe your whole app structure at the highest level as nested components, passing in props directly to remote descendants, and using children to render injected components at the branch levels. However, taken to the extreme, this would make your container component really complicated, especially for intermediate components that have children of more than one type. Not sure if this is really viable at all for that reason.
React context
As first mentioned by #mattclemens, you can use the experimental context api to decouple your intermediate components. Yes, it's "experimental". Yes, the React team definitely doesn't seem to be in love with it. But keep in mind that this is exactly what Redux's connect uses to inject dispatch and props from selectors.
I think it strikes a nice balance. Components remain decoupled, because branch components don't need to care about the descendants' dependencies. If you only use connect at the root to set up the context, then all the descendents only need to couple to React's context API, rather than Redux. Components can freely be rearranged, as long as some ancestor is setting the required context properties. If the only component that sets context is the root component, this is trivially true.
The React team compares using context to global variables, but that feel like an exaggeration. It seems a lot more like dependency injection to me.
For information that is global to all of your "dumb" components, you could use react contexts.
A contrived example
// redux aware component
var ChatApp = React.createClass({
childContextTypes: {
language: React.PropTypes.string
},
getChildContext: function() {
// or pull from your state tree
return {language: "en"};
},
...
}
// dumb components
var ExDumb = React.createClass({
contextTypes: {
language: React.PropTypes.string
},
render: function() {
var lang = this.context.language;
return ( <div /> );
}
});
In response to the comments, redux uses this context approach in their react-redux library.
And more abstractly for use outside of react, you could use some sort of pluck or selector function on the state tree, and return only a subset of the global state needed by dumb components.