what's the best way to share user data between components? - reactjs

I have a query i.e:
query me {
me {
username
email
}
}
now I need to share this data between components.
I guess I can:
create HOC withUserData and wrap other components
create a render prop component and wrap other components jsx
else?

It depends on where are places you want to share them, I mean if you want to share data in the same branch of the component tree, you can have a Container Component at the top ( Which holds your state and pass the data has props to the levels below).
If your components branch is very complex and it needs to travel down many levels then its a pain and not recommended too, in this case, consider using Context API
https://reactjs.org/docs/context.html
I would not recommend a HOC for this, HOC is not meant to share data, its meant to share re-useable functionalities.
Please check this, this has a bunch of best practices https://www.toptal.com/react/tips-and-practices
Well REDUX is another way but I would not recommend using REDUX looking at your need.
When to use REDUX?
Basically, you need to be using REDUX, when keeping the state in a top-level root component is no longer sufficient, like for example : ( you have two branches out from root component, one of the child components in branch A wants to access some state in branch B's child, then you need to move it to the root component and again pass it down, such cases are apt for REDUX ).

HOCs and Render props are not something that you would use to share data among components since each wrapper will have a different instance of the data whenever you create a component like
const MyComponentWithData = withUserData(MyComponent);
You would use HOCs and Render props mostly to provide a functionality which can be relevant to more than one components like detecting click outside of the component, or a PrivateRoute for authentication and so on.
However in order to share data you have options to use React Context, Flux or Redux. With the usage of React redux you can keep data in a store and read and update data from the components that want access to it. However if your app is not using Redux and you would want to share data only for a part of the application, you can simply make use of React Context. For more details on how to use it, you can read about it here

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.

If we don't make a React component as Presentation component, isn't this component not easy to be re-used?

I don't quite understand Dan Abramov's 2019 comment in his article Container vs Presentational component.
Is it true that we should still make component Presentational component so that we can re-use them? If we start making components that have an app state, then this component cannot be re-used easily, because then having two of such component on the same page will let them interfere with each other.
So the component can have state, but only "component state", such as whether the comment box is expanded or not, or even the current text in the comment box, etc. It should not be tightly coupled with a certain state in the app. Because then we cannot really re-use this component, unless it is for sure a singleton in the whole app, which mean there is no re-use.
So does it really mean we should write our components so that it is re-usable, and let other component pass in the App data as "props"? This way, we can re-use our components just by passing in different props (and dispatch) from the outer container.
So for our re-usable component, it doesn't matter it is Container or Presentational or combined, just as long as a even higher container can pass it the props and dispatch and let us re-use the component. Is that what Dan really means?
IMHO this statement was more about granularity and separation of biznes logic ... container usually manages some app specific dataset with some set of presentational components.
Of course container component can be reused, too. F.e. list of user followers can use common Apollo client (graphql) as long as our backends are composed using the same (shared) schema (by microservices/federation). It can be freely used in different apps and by using render props we can change its look/behaviour.
It's about reusability in general, it's much easier for stateles (presentational) and locally managed state components (class or functional).

Can I use state in components while using Redux or Redux store?

**Is it OK to Using a component state for just to handling form data, while the main data and other stuff of the application will be stored in the Redux store?
I don't want to use redux-form instead manually dispatch it to the reducers**
Redux comes into the picture when we want to manage the state across different component. It provides a centralize store where state of all the components are managed.
When talking about forms, in most cases form data is only limited to the component is which is being used. So, in that type of scenario there is no need to link them to centralized store using redux. A simple way is to store them in the component state and get it processed. Afterwards, you can store the output of that in redux store according to your needs.
It is okay to do that. You can keep a local state in the component. state = {} in class components, const [localState, setLocalState] = useState() for functional components.
Or you can use custom hooks for handling your local state needs. Check out useInput or useForm custom hooks that are developed by the community.
Yes of course. Some things go best in component state, some go best in a parent component, some go in Context, and some go in Redux. There is little use in putting everything in Redux, it just causes a lot of boilerplate and every component tries to update when the store changes.
You put things in Redux when different components that are at different places in the HTML tree use the same data, and it changes during the app's lifetime (things like the user's language don't change often and go in Context). You use it when you want to store your app's state to restore it later (which exact menus are currently open or closed is usually not that important) and when you want to keep track of state changing using the Redux dev tools.

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