Hooks equivalent of container components in React Redux - reactjs

I am new to using react hooks api.
Earlier I used to distinguish container components and presentational components.
The project directory structure was according to this distinction.
Container components used to inject store state and action creators to the component through props.
With hooks I have been left clueless how the directory structure should be and whether the hooks should be injected to the component through props or simply imported inside the component.
Should there be a containers and components distinction.
The redux documentation which describes container and presentational components also doesn't seem to be updated for hooks.
Any relevant article or answer is welcome.

About the separation between container components and presentational components, Dan Abramov (working on ReactJs, co-author of Redux and Create React App) wrote this in Presentational and Container Components :
Update from 2019: I wrote this article a long time ago and my views have since evolved. In particular, I don’t suggest splitting your components like this anymore. If you find it natural in your codebase, this pattern can be handy. But I’ve seen it enforced without any necessity and with almost dogmatic fervor far too many times. The main reason I found it useful was because it let me separate complex stateful logic from other aspects of the component. Hooks let me do the same thing without an arbitrary division. This text is left intact for historical reasons but don’t take it too seriously.

As user adel commented, there is now hook equivalents of react-redux stuff. To read redux state, instead of connect, you can use useSelector.
import { useSelector } from 'react-redux'
..
const somePieceOfData = useSelector( state => state.path.to.data )
About container components, you can still seperate your container, using react-redux hook stuff. There is nothing about that with react-redux.

I am also running into the same problem now and was looking for some nice resources in that , but here what I've reached:
There is no big need for the distinction now between UI and container components, you can use custom hooks for the same purpose and you will have fewer lines of code and more readable one. From what I've read (i didn't experiment this yet) but it should have better performance as using functional components including custom hooks inc the app performance.
Take a look at this :
https://dev.to/jenc/discuss-react-hooks-and-life-after-the-container-component-pattern-5bn

Related

React design patterns using redux

I am developing using Presentational & Container design pattern.
Here I have one question.
If all components are connected to the global store, there is no need to divide the components into Presentational components and Container components.
Is there any reason to divide them?
The reason I inquire about this is that if you develop using the Presontational Component & Container Component design pattern, you have to pass props from the parent component to the child component, and I think this is a part that can lower development productivity and cause errors...
So I would like to connect all the components to the global store and use them.
What other problems are there in this case? For example, performance...
"Presentational components" and "Container components" are a pretty old concept that stems from the pre-hooks area. It was nice do have presentational components that could be tested purely on their own - but with the rise of hooks, React components generally house a lot more logic and in most cases, this is fine.
Redux is still a good way of generally moving most logic outside of components - even without a distinction between "presentational" and "container" components. See the Style Guide on this topic
I'd generally recommend reading the Redux Style Guide and if you are still using old-style Redux with connect and switch..case reducers, also read why Redux Toolkit is how to use Redux today
If all components are connected to the global store, there is no need to divide the components into Presentational components and Container components.
First off, any component can be connected to the store (as in, the redux context is available), but you don't need to access state or dispatch actions in every component. So I'd define "connected component" as one that actually uses state or actions.
Is there any reason to divide them?
I'd recommend to simply read state or dispatch actions if and where you need to.
This design pattern from the early redux days is honestly not super helpful and got watered down a bit with hooks and function components (quicker to throw in a useSelector than setting up a connect()ed component).
In some cases you can separate abstract UI logic from global state. As #pailhead pointed out in a comment above, there could be a UserStatus component that defines two different colors for logged in vs. logged out - without being connected to redux. Instead a <UserStatusIndicator> is connected to redux and passes props.isLoggedIn, which is read from state.user.isLoggedIn, to the <UserStatus> component. Imagine the UserStatus component is also reused in an admin panel list that shows the current status of all users in the system - so it's rendered 50 times but independent from redux.
you have to pass props from the parent component to the child
component
Definitely don't do excessive prop drilling, connect these children to redux instead.

What's the purpose of a React Functional Component when it can be used to modify state?

I am new to React and learning it. From this link:
There are mainly two components in React:
Functional Components also known as Stateless component
Class Component also known as Stateful component
and it seems that functional components are the rage these days e.g., I inherited some code and it uses functional components everywhere. The same article is then saying:
... a functional component is just a plain JavaScript function, we
cannot use setState() method inside component. That’s why they also
get called functional stateless components. ... useState can be used
to store state in a functional component.
and I do see tons of code using useState in functional components to modify state. Can someone explain this to me?
Answering my own question.
Functional components were referred to as stateless components but its no longer correct to think of them as stateless. This link from official documentation explains it:
You might have previously known these as “stateless components”. We’re
now introducing the ability to use React state from these, so we
prefer the name “function components”.
To answer the second part of the question, functional components are indeed the rage these days because that's the official guidance and recommendation. From this page:
In the longer term, we expect Hooks to be the primary way people write
React components.
Also see this page for some background and comparison of class components vs. functional components.

Should class components still be used when functional components with hooks exist in React?

Hi I'm very new in React. I've started learning React in the past 2 weeks, and I'm currently making a website using the MERN stack with a friend. I've been using class components whenever I saw a need for maintaining states, but I just discovered that hooks can mimic React classes and supposedly reduces code length, increases readability, and creates more maintainable code. So I'm just wondering, should class components be used in React as of 2020 when hooks exist? What use cases do classes cover that aren't covered by functional components?
it's preference thing but the community is moving towards hooks.
Hooks + other features can pretty much cover everything done in hooks
e.g.
useEffect => componentDidMount, componentDidUpdate, componentWillMount
useState => this.setState({})
React.memo => shouldComponentUpdate
some things are easier in classes than they are in hooks at the moment. like the second argument in setState is a callback to ensure that state is changed before executing. this is possible in hooks but it's not quite as clean as that
Hooks are meant as a complete replacement for class components. From react docs,
We intend for Hooks to cover all existing use cases for classes, but we will keep supporting class components for the foreseeable future.
Reading the page linked above about the adoption strategy, the intent behind hooks - would be a great place to understand and form an opinion.
Personally, I love hooks. And haven't used class components since hooks were introduced. I am yet to find a use-case where I needed to use a class component because hooks couldn't satisfy the ask.

Should container get value from props?

I have an app structure like this with redux:
app
|-router
| — dashboard container
| — — dashboard component
| — setting container
| — — setting component
Consider the two containers, if I need to get translation text from the store which way should I used?
(1) Connect to redux store on router and pass down to containers by props
(2) Each of the container connect to redux store individually
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
https://www.reddit.com/r/reactjs/comments/4azg7q/using_redux_how_do_you_handle_subcomponents_of_a/
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.
if the translations are dispatched from router then use connect if they are not fetched or updated by dispatching an action and will never update passing them is better.

React-redux connect: root component connect vs multiple connects [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.

Resources