React (Native) Architecture and state management - reactjs

Trying to understand the best practice for React/React Native state. Coming from the Java world, I tend to follow MVC/MVVM in my applications, but reading about other approaches makes me wonder if I am designing my application properly.
Premise:
App mostly for consuming video and audio content, storing user statistics and progress
React Native Firebase from invertase.io
Redux used for storing data structure from Firebase Realtime Database
My current approach:
If a React Component needs data, it gets it via Redux or parent component via props.
If a component needs to manipulate/fetch more data, I have separate viewmodel classes (Typescript files with no dependency to React/RN) that are accessed in a component.
If the viewmodel gets new data from somewhere, the component state gets it via Observer pattern by implementing an interface
If data needs to be persisted to Redux and/or Firebase, the viewmodel does it. I pass the Store object from the component
Approach I read/heard/discussed:
All data from/to components is received/sent through Redux
All data manipulations are done in Redux Actions
No separate controllers/viewmodels
I don't have too much history with React Native, so I am trying to understand whether the latter approach is actually superior for some reason.

These talks helped me understand Flux at a fundamental level. The basic idea is unidirectional data flow. Watch the talks and pay attention to them.
You don't need Redux to implement Flux– I used Alt.js instead.

Related

Want to know about react & redux

What is the basic difference between react and redux? is react and redux is same? why we should use redux? Finally why it's called react-redux?
I want to know this i just confused between this two.
You must be pretty new to web development. First of all, welcome !
React and redux are pretty different beasts, but have often been used together to make state management easier in React apps.
React is a front-end web framework, it allows you to create a wide range of web apps using JSX (React's way of fusing Javascript and HTML). This is a gross oversimplification, I encourage you to read the documentation.
Redux is a state management library. With it, you can define one or many stores, containing a state (basically an object that holds any data you need), actions (methods to alter or retrieve the current value of the store) and to subscribe the state's changes at a global level. Again, the Redux documentation should have most of the answers you're looking for.
React and redux are often used together, mainly through the use of the react-redux package, since Redux offers a global, reactive state, enabling you to share data between React components anywhere in your app without having to pass props.
Now tough, you could achieve similar functionnality without Redux entirely, using React's own Hook and Context APIs. Although the logic behind these is a bit more involved, it allows for far more flexibility.

Redux and React context together

I am building a web app where redux is configured and app is fairly large.
Now I want to store some user preferences which will be available as part of an API respopse.
As this data is required to the majority of components I am planning to store data in the context and wrap application using the context.
I have Few questions regarding approach.
Will considering context impact the performance?
As Redux is already configured which internally uses the Context. So should we continue to use redux for user data.
Is it good practice to use Redux and Context together.
Context and Redux are very different tools that solve different problems, with some overlap.
Context is not a "state management" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components. It's up to you to decide what that value is, and how it's created. Typically, that's done using data from React component state, ie, useState and useReducer. So, you're actually doing all the "state management" yourself - Context just gives you a way to pass it down the tree.
Redux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed. It also gives your whole app the ability to access any piece of state in any component.
In addition, there are some distinct differences between how Context and (React-)Redux pass along updates. Context has some major perf limitations - in particular, any component that consumes a context will be forced to re-render, even if it only cares about part of the context value.
So, yes, you can use them both in the same app, in the same way you can use a hammer and a screwdriver together on the same construction job.
For more details, see my posts:
Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux)
React, Redux, and Context Behavior
A (Mostly) Complete Guide to React Rendering Behavior
Will considering context impact the performance?
Since you want to share user preferences that (I guess) do not change often, you could use a React context to share that data.
But performance issues arise when you put multiple different data in one React context that update at different rates. This is because every component that uses the context will be rerendered even if the part of the context it is interessted in did not change. In this case you can split the context and use one context for each part of the data.
Since you want to use the context to share an application state, you should use Redux. In Redux you use selectors to select a part of the application state. This useSelector hook is implemented in a way that it only triggers a rerender of the component if the selected part changes. You can even pass it an equality function if you want to change the way state change is detected.
As Redux is already configured which internally uses the Context. So should we continue to use redux for user data.
I would say: yes, continue with Redux.
Since you already use Redux you should not spread your application state management over different concepts. Put the user settings in the Redux store (like any other application state) and don't handle them special.
Is it good practice to use Redux and Context together
Well, Redux is based on the React context. So if you use Redux it is already a good practice.
If you mean using both for application state management, I think you should go the Redux or the React context way. Mixing them makes it harder to understand where state is managed.

React components with shared state that are far away

I am new to React so please excuse me if this is a noob question but I really could not find the answer in the DOCs or elsewhere.
Let's say I have two buttons with a counter that share the state but are far away from each other in terms of the placement in the UI.
The documentation says the common owner component for both buttons should own the state. It makes sense if the components are next to each other like in the example but what if my buttons are each part of a different UI group and are far away in terms of nesting? My state holder would be the root of the document and I would have to pass a handler function down through many layers. And what if I need to add new component somewhere else that also needs to know the state? Would I have to modify all the parent components in the way to pass the state down? That is tremendously impractical.
Without React I would have some global Subscribe/Publish pattern like jQuery Observer and all UI elements could subscribe/publish to it regardless of their nesting position.
How does React solve this?
Related question: If I need to load/save the state to DB, how do I pass a reference of the controller (or Whatever) to each React component that stores the state?
1 for global state you may use REDUX
Redux is a predictable state container for JavaScript apps
for connect/subscribe component with that state ,you should use react-redux
If components are far away in terms of nesting, you may connect/subscribe them to redux store, and take only neccessary part of state. They will update if only neccessary part is changed.
article that explains how you can do your case
to learn how to use redux you can watch this videos from creator of redux (Dan Abramov)
1.getting-started-with-redux
2.building-react-applications-with-idiomatic-redux
3.I definitely recommend to you discordapp rectiflux channel. because you allways can ask any question online.(there you can find contributors of that tools)
2 alternative way that less verbose then redux is MobX
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). The philosophy behind MobX is very simple:
Anything that can be derived from the application state, should be derived. Automatically.
I suggest to look at the Flux stores. In short, stores are like model in your application. You can listen to change (subscribe) and also modify their properties (publish). You can see how it was done in example app.
A better option is to go with Redux.
Redux is enabling use cases like yours in a way simpler fashion :)
It will help you with all the state and make your life much easier.
Some good resources for learning:
The Redux Website
Video courses from Dan Abramov, the creator [Free]
Awesome course on Udemy [Not free]
Building Applications with React and Redux in ES6
And finally take a look at this youtube series [Free]
Managing state in the middle layers of your app should be avoided where possible. This data belongs in a store, which holds the global state of the app. Then each component accesses the state via its props.
The naïve approach to get the data down to the component is to pass the store through all the layers of your app "manually", i.e. through props.
Smarter alternatives exist, which use connected components, that access the global state through the context (as opposed to the props). Typically, the presentational component (your button component) is wrapped in a container component that handles this connection to the store, then passes the data in via props.
There are numerous frameworks that facilitate this process, links to which are already provided in the other answers.
If you are trying to share simple states, try this ( I am the author): react-provide-state
Otherwise I will recommend Redux. It has become the most popular tool for managing application states.
In the applications being working on, we use Redux to manage the main application states and almost all other states. But we use 'react-provide-state' for simple, UI only states like Modal, Checkbox states.

What is NoSQL stack for React.js?

I want to know if there is a NoSQL library or framework stack for React.js just like Angular and MongoDB. I dont really understand flux. So any comment will be helpful. Thank you.
flux is an application state container. Not something like mongoDB.
Flux lets you have an application wide state, not dissimilar to react component state.
mongoDB is a DB that persists. Only data that defines current application state should go into the flux store. It does NOT persist.
Application state example
Suppose you are using react to build a game using multiple components.
React components have a uni directional flow of data from parent to child as props.
So if the child component decides to advance you to next level, all it has to do is, change the game level stored in application state and the parent component can read from the store and do the needful for new level.
Flux is basically a library that makes it easier to have an application wide state. Since the component state is limited to a single component.
There is another library that helps you manage application state called redux. http://redux.js.org/
It's easy to understand :)
PS: You can use mongoDB or Redis or any DB for that matter in your backend. Flux is not your db. Personally, I'd rather use Redis.
I believe angular is a framework. Whereas React is a library. You have the freedom to choose the technologies you want to pair it up with.

Why do we need Flux with React?

I don't understand why we need Flux with React as React itself let's us maintain the state of the application. Every component has an initial state and the state can be changed by user actions or any other asynchronous JavaScript.
Why is React called as only a view library when it can let's us define state of the application and also update view whenever state changes. This is not what a view does....its what complete MVC does right?
For example: here is an Todo app build only with React and here is an Todo app build with Flux and React.
If we can build the Todo app with React only then why do we need Flux?
In theory you don't need flux.
In small applications you don't need flux for sure.
But what if your application consist of hundreds components? And one of your component is form. User populate this form and you send its content to server. And get response from server with new data.
And assume that this response data and data from form are necessary to other components.
Without flux:
You can move your data to root component and then distribute it down to all components. But if you need to distribute data from many other components too? This makes your application very complex.
with flux:
You move your data to stores, and all components which are interested about this data, can get it from there. You have better control on your application and source data.
I prefer redux (only one store and one source of truth)
edit:
Why is React called as a view library even if it can handle application state?
MVC is a software architectural pattern. It divides a given software application into three interconnected parts (models, views, controllers).
If we think about react and MVC it fit as View. But this is nothing wrong. It doesn't mean that you can use it only for views. It allows you to create normal applications.
But in other hand you can use it as view for other frameworks (for example you can use it with angular).
In other words it is very flexible library for many uses.
You don't NEED Flux the same you don't need MVC. They are both architectures and you can of course build something without using either.
Would you build a non-MVC app in 2016? Probably not, that doesn't mean that people didn't do it in the past.
Flux is awesome! But as most things in the tech industry is not always the right decision, things vary in a project requirement basis.
Probably the biggest selling point of Flux is that it tries to enforce the data flow in one direction, this means that you know for sure where the data is coming from. In a non-flux app the data for a component could be an own property, a property passed down the component tree, a local state variable, a state variable result of calling an API.
With Flux: "where does the data come from?". Answer: from the stores. Redux takes this further and only uses a single store.
Flux has been criticized because you need a lot of boilerplate code but again is a matter of tradeoffs.
At the end is always your call depending on your project needs.

Resources