Singleton Class vs Statemangement tool like Redux for App State - mobile

Can somebody explain to me why you would ever use a statemanagement tool like Redux or the Provider library instead of just creating your own Singleton class to hold the state of your application?

Redux is so much more than a singleton. It gives you pub/sub, time-traveling to prior states (especially good for debugging) and an open-ended api to plug in your own functionality. It is an especially good place to handle side effects.
In react, you can't just "plug in" your own data structure and expect everything to update properly. React updates on an as-needed basis. In order to do that, you have to use the React api in one form or another (context api, hooks, etc.).
Any singleton implementation you do will essentially be a subset of redux's functionality. In an overwhelming majority of cases, you will need all of redux's features (along with 3rd party middlewares) in a long-term production application.

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.

what is a generally acceptable way to structure a service layer in a reactjs project?

I'm using axios.get() to call an api endpoint in one of my components. I need the ability to encapsulate this endpoint call so I can reuse this implementation by calling it from several different components.
What is a generally acceptable way to structure this type of implementation in a React project? For example, would it be generally acceptable to group related api calls into js files in a src/services directory at the same level as src/components?
It would be acceptable to create a utils or services directory and group related API calls. However it is important to remember that with async requests you need to consider the components calling the api service utils might un-mount. This might result in warnings or errors if not handled properly. A possible way to handle this might be to only execute callback functions if component is still mounted tracked via a state variable in a useEffect hook.
A more modern react approach might be to leverage hooks and react context for data handling. You could create a DataContext with a useReducer hook to fetch or push data for example.
(see https://reactjs.org/docs/context.html)
There are many way to do this.
Redux. It's old way is that you need to use redux style.
Hooks. Starts from React 16.8 version.
I will recommend to you use hooks. It's more useful and guarantee true way.
3 years ago i lived in Redux paradigm and every time write the monkey code thinking about consistent Redux store state.
Please try this one react-async package.

Using Context API in a project I would have previously used Redux in - async action creators?

So most of my projects are simple enough that Redux has been total overkill (even though it's worked really well always) - I am going to use Context API on a new project (it will easily do the job, and it's way easier to explain to other devs and get them going on) - Redux has Thunk to handle async actions. I think I understand things well enough to reason that async actions will not be a problem for Context API - Redux Thunk doesn't actually add async functionality to Redux - it simply makes the syntax more palatable. So my reasoning says that Context API will be able to handle any async actions as long as I write code to correctly deal with them. Is this right, or do I need to stick to Redux with Thunk if I want to handle async actions effectively?
I had similar question myself and came across this article that talks about a major difference between Redux and the Context API:
From https://www.academind.com/learn/react/redux-vs-context-api/
The Context API (currently) is not built for high-frequency updates (quote of Sebastian Markbage, React Team), it’s not optimized for that. The react-redux people ran into this problem when they tried to switch to React Context internally in their package.
My personal summary is that new context is ready to be used for low
frequency unlikely updates (like locale/theme). It’s also good to use
it in the same way as old context was used. I.e. for static values and
then propagate updates through subscriptions. It’s not ready to be
used as a replacement for all Flux-like state propagation. ---
Sebastian Markbage
So for the moment, it seems like you might want to look into using React Context for low-frequency updates (e.g. theme changes, user authentication) but not use it for the general state management of your application.
Hope this helps.

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