Redux & RxJS, any similarities? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I know Redux is a better "implementation" of Flux, or better saying it's a redesign to simplify things (application state management).
I have heard a lot about reactive programming (RxJS), but I haven't dived to learn it yet.
So my question is: are there any intersection (anything in common) between this two technologies or they are complementary? ...or totally different?

In short, they are very different libraries for very different purposes, but yes there are some vague similarities.
Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular.
RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises.
Reactive programming is a paradigm (way of working and thinking) where data changes are observed from a distance. Data is not changed from a distance.
Here is an example of changed from a distance:
// In the controller.js file
model.set('name', 'George');
The Model is changed from the Controller.
Here is an example of observed from a distance:
// logger.js
store.subscribe(function (data) {
console.log(data);
});
In the Logger, we observe the data changes that happen in Store (from a distance), and write to the console.
Redux uses the Reactive paradigm just a little bit: the Store is reactive. You do not set its content from a distance. That's why there is no store.set() in Redux. The Store observes actions from a distance, and changes itself. And the Store allows others to observe its data from a distance.
RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this "observing from a distance" pattern.
To conclude, very different things for different purposes, but share some ideas.

They are very different things.
RxJS can be used to do Reactive Programming and is a very thorough library with 250+ operators.
And Redux is as described on the github repo "Redux is a predictable state container for JavaScript apps".
Redux is just a tool to handle state in apps. But in comparison you could build a full app in just RxJS.
Hope this helps :)

Redux is a just a state management library coming with well defined standards for update operations. As far as you stick with the standards you can keep your data flow sane and easy to reason. It also brings the ability to enhance the data flow with middlewares and store enhancers.
RxJS is a toolkit for reactive programming. You can actually think of every thing happening in your app as a stream. RxJS gives a very rich tool set to manage those streams.
Where RxJS and Redux intercepts? In redux you update your state with actions and obviously these actions can be treated as streams. Using a middleware like redux-observable (you don't have to) you can implement your so called "business logic" in a reactive way. Another thing is that you can create an observable from your redux store which sometimes might be easier than using an enhancer.

To put it in short:
Redux: Flux inspired Library used for State Management.
RxJS: It is another Javascript library based on the reactive programming philosophy, used to deal with "Streams" (Observables, etc.) [Read about Reactive Programming to understand the Stream concepts].

I just wanted to add some pragmatic differences from when I did Redux-inspired RxJS-code.
I mapped each action type to a Subject instance.
Each stateful component will have a Subject that is then mapped into a reducer function.
All reducer streams are combined with merge and then scan outputs the state.
The default value is set with startWith just before the scan. I used publishReplay(1) for states, but might remove it later on.
The react pure render function will be to only place where you produce event data by sending in all the producers/Subjects.
If you have child components, you need to describe how those states are combined into yours. combineLatest might be a good starting point for that.
Notable differences in implementation:
No middleware, just rxjs operators. I think this is the biggest power and weakness. You can still borrow concepts, but I find it hard to get help from sister communities like redux and cycle.js since it's yet another custom solution. That's why I need to write "I" instead of "we" in this text.
No switch/case or strings for action types. You have a more dynamic way of separating actions.
rxjs can be used as a tool elsewhere, and is not contained to state management.
Less number of producers than action types(?). I'm not sure about this, but you can have many reactions in parent components that listen to child components. That means less imperative code, and less complexity.
You own the solution. No framework needed. Good and bad. You will end up writing your own framework anyhow.
It's much more fractal, and you can easily subscribe to changes from a sub-tree, or multiple parts of the app state tree.
Guess how easy it is to do epics as redux-obseravble do? Really easy.
I'm also working on much bigger benefits where the child components are described as streams. This means that we don't have to complect parent and child state in the reducers, since we can just ("just") recursively combine the states based on the component structure.
I also think about skipping react and go with snabbdom or something else until React handles reactive states better. Why should we build our state upwards just to break it down via props again? So I will try to make a version 2 of this pattern with Snabbdom.
Here's a more advanced but small snippet where the state.ts file builds the state stream. This is the ajax-form component's state which gets an object of fields (inputs) with validation rules and css styles. In this file we just use the field names (object keys) to combine all the children's states into the form state.
export default function create({
Observable,
ajaxInputs
}) {
const fieldStreams = Object.keys(ajaxInputs)
.map(function onMap(fieldName) {
return ajaxInputs[fieldName].state.stream
.map(function onMap(stateData) {
return {stateData, fieldName}
})
})
const stateStream = Observable.combineLatest(...fieldStreams)
.map(function onMap(fieldStreamDataArray) {
return fieldStreamDataArray.reduce(function onReduce(acc, fieldStreamData) {
acc[fieldStreamData.fieldName] = fieldStreamData.stateData
return acc
}, {})
})
return {
stream: stateStream
}
}
While the code might not say much in isolation, it shows how you can build state upwards, and how you can produce dynamic events with ease. The price to pay is that you need to understand a different style of code. And I love to pay that price.

Related

How `this.props` is defined and information is saved into global Redux state

I am new to react and Redux and utilize a react project on GitHub: overcode/rovercode-ui to learn react and Redux. I have some questions about it.
For each component in fold component, I cannot find why the component has so many props. For example, for Workspace component, at the end of file \component\Workspace, it checks the props of Workspace component. I wonder where these props come from (namely where these props are defined), e.g., the code props.
Action createProgram defined in file \actions\code.js use an asynchronous POST method to create an id for newly created program. However, in the sub-reducer \reducers\code.js, when action.type equals to CREATE_PROGRAM_FULFILLED, id will be extracted from action.payload to save into global state. So, how the id is saved into the global state and action of type CREATE_PROGRAM_FULFILLED is dispatched?
Can anyone help me analze this project? Thanks a lot :)
Hello and welcome to React - Redux universe. I am sure you will love it but regardless of your background or experience level, you have to make your peace with the fact that there is a learning curve and when you are especially new to thinking in terms of components, developing a different mindset takes time. Don't worry, we all been there and it will past. Just give yourself some time.
I am afraid, even if we spend some time together to analyze this project, I don't think that it would make your life easier in terms or learning React or Redux. Analyzing this project is more like helping a beginner foreign language learner to translate a story. It might help you to understand the story, but at the end you won't probably be able to write a new story in the language you are trying to learn.
That said, I'll try to briefly provide answers to your questions and try to point out why analyzing this specific project will not be as helpful as you would expect
1) In order to comprehend where all these props come from, you need to recognize the following pattern that is
connect(mapStateToProps, mapDispatchToProps)(Workspace))
so basically, thanks to connectfunction, you can connect your component directly to the redux store (you name it as global state)
For instance, let's take a look at the following snipped from the file https://github.com/rovercode/rovercode-ui/blob/alpha/src/components/Workspace.js#L36
const mapDispatchToProps = (dispatch, { cookies }) => ({
updateJsCode: jsCode => dispatch(actionUpdateJsCode(jsCode)),
Basically, thanks to mapDispatchToProps we return an object. And since we use mapDispatchToProps as a parameter of connect function, connect function takes the properties of the returned object and passes them to component as props.
Thanks to that, in the following line https://github.com/rovercode/rovercode-ui/blob/alpha/src/components/Workspace.js#L293 we could manage to extract updateJsCode from the props
So, good news and bad news. In order to explain this to you, I need to spend some time to build a fundamental understanding of what is props, what is higher order components, what is redux, what is actions etc. etc. Once you learn the fundamentals first, it is easier to connect the dots.
2) So in order to answer this question, I need to go through the codebase to understand the architecture of the project. The important thing to be aware of is that, even though there are some certain best practices, every project has its own data structure and architecture. It is up to the creator of the projects to make a decision in terms of component architecture, data structure etc. etc. When you are new and try to understand the technology by checking existing projects, you might end up confusing yourself big time and treating the architecture of those project as source of truths.
My humble suggestion to you is, first things first, try to focus on React without Redux. Because most of the time, you might not even need a state management depending on the scope of the project (again a decision needs to be made by the team etc.)
The things that you might want to learn with React are
1) Parent-child-sibling component relationships
2) React Hook api (relatively new, but usage is increasing dramatically so as a new learner you should definitely take a look)
3) If you want to understand some "old" project and tutorials you might also want to learn about life cycle methods
4) What is presentational component vs container component
5) Higher order components
Once you are comfortable with the fundamental of React, you can then continue with Redux. I bet things will be way more easier
If you need more suggestions, send me a message so I can try to provide you some resources
Thanks for your answers. After reading your reply and learning related conceptsI, still have a question. You explain that connect(mapStateToProps, mapDispatchToProps)(Workspace)) connects component directly to the redux store and use the example to illustrate that mapDispatchToProps connects actions to component. So my understanding is mapStateToProps connects state of redux store to component. e.g., code code property of this.props comes from the state of redux store, returned by reducer. Is it right?

When should I use Vuex?

Now I start to learn vue, and I'm creating SPA for editing database. Now I can't understand where I should use a Vuex. I can use props and $emit everywhere and it can help me find needed parameter. So for what case I should use Vuex?
According to this awesome tip from Vuedose blog
Vue.js 2.6 introduced some new features, and one I really like is the new global observable API.
Now you can create reactive objects outside the Vue.js components scope. And, when you use them in the components, it will trigger render updates appropriately.
In that way, you can create very simple stores without the need of Vuex, perfect for simple scenarios like those cases where you need to share some external state across components.
For this tip example, you’re going to build a simple count functionality where you externalise the state to our own store.
First create store.js:
import Vue from "vue";
export const store = Vue.observable({
count: 0
});
If you feel comfortable with the idea of mutations and actions, you can use that pattern just by creating plain functions to update the data:
import Vue from "vue";
export const store = Vue.observable({
count: 0
});
export const mutations = {
setCount(count) {
store.count = count;
}
};
Now you just need to use it in a component. To access the state, just like in Vuex, we’ll use computed properties, and methods for the mutations:
<template>
<div>
<p>Count: {{ count }}</p>
<button #click="setCount(count + 1);">+ 1</button>
<button #click="setCount(count - 1);">- 1</button>
</div>
</template>
<script>
import { store, mutations } from "./store";
export default {
computed: {
count() {
return store.count;
}
},
methods: {
setCount: mutations.setCount
}
};
</script>
Update: Since this answer was written, things changed. If you're considering using Vuex today, don't. Use Pinia instead. Here's a decent answer outlining why you should favor Pinia over Vuex. However, what I said about the Redux pattern below, still stands.
The main purpose of using Vuex (which is Vue's version of Redux) is state (or data) management. In layman's terms, it's having a single source of truth (for your data).
It opposes the common pattern of emitting an event when data changed so other parts of the application can keep their data in sync with the current component's data.
Rather than allowing one particular component to change the data directly, you delegate the change to a separate module: the store. Any component using that data will be notified about the change. This becomes extremely useful in complex applications, where the common emit pattern runs the risk of creating cyclic update loops.
Apps using the Redux pattern benefit from:
predictability of outcome,
ease of testing
code maintainability and scalability
separation of concerns
ease of debugging (time travel: the ability to undo or replay a particular change for debugging purposes).
In short, it gives developers control and confidence, as it makes understanding and modifying complex code, data or app behavior significantly easier.
Like any other pattern (or system, or tool), the Redux pattern can be over-used. It should be obvious you don't have to keep data that's only used by one component in the store. Since no other component needs to know about any changes to that data, one should manage it in the component using it.
Vuex allows organisation of data into modules so you can keep everything tidy and maintainable.
Last, but not least, one of the most useful benefits of using the Redux pattern is making SSR (server side rendering) implementation a breeze. SSR greatly improves optimization and user experience and increases the perceived performance of the application.
Yes, you can do anything without the use of Vuex, but with time, if your application is getting larger then it would be difficult to maintain,
according to vuex documentation,
problem one, passing props can be tedious for deeply nested
components, and simply doesn't work for sibling components. problem
two, we often find ourselves resorting to solutions such as reaching
for direct parent/child instance references or trying to mutate and
synchronize multiple copies of the state via events. Both of these
patterns are brittle and quickly lead to unmaintainable code.
Hope it answers your question.
Look at the vuex documentation; it describes all the reasons why/when you want to use vuex https://vuex.vuejs.org.
For instance, multiple components require the same information, controlling mutations, validations, etc.

React Component State management using redux

So Basically, I came across many articles where they are referring to manage state via flux or redux.
I wanted to know that how about UI component having its own state? Is it good practice to let redux manage the Api call and success toast messages etc. but UI components should have their own local state?
Kindly someone elaborate what is the best practice in industry?
Though the question calls for opinion, I am going to leave my answer. There is no standard best practice regarding this. It boils down to convenience and ground rules of your team, if there are more than one people writing the code.
I use Redux quite a lot. However, I won't refrain from using local state in components.
Form handling like input onChange handlers require local state. It is not performant to use global state for onChange handlers.
Reusable component uses local state. Again, it boils down to whether the reusability is a technical reusability or business reusability. If you are developing a custom scrollbar component, use local state. However, if you are using a comment form which is used everywhere in your application, use global state.
I prefer to have most of the stuff in global state. I use redux thunk as well. In redux thunk, it is possible to access global state within the thunk function. This is quite useful as it avoids the reliance for props / context being passed all around.
I do keep some simple things in local state -- for example, show / hide some stuff. I don't mind waiting for promises to resolve before hiding some stuff using local state.
Overall, the decision to use global state vs local state is primarily based on convenience. There are no standard rules other than what you and your team are comfortable with.
React is a way to declaratively deal with UI. There are some rules of the framework like state, props, context. It is left upto the developer to make the UI declarative and performant based on these primitives. How, a developer does it does not matter as long as the code is maintainable and understood by others.
After asking many professionals and industry developers, I came to know that managing state through redux depends on your application scope.
but more importantly, If I am working on enterprise Application then the application state must be managed through redux.
Now the question is what should be kept in our redux store. well, you can store almost anything in redux store but better to manage the local state of a component as well. for instance, opening a component Boolean should be managed in local state or any string or header name etc.
Good question! The answer is usually "it depends", but there are clear cases when you'd probably prefer to use one over the other.
Use Redux for storing state relevant to the application. E.g. the current page/panel that should be shown. As you mentioned, showing a notification/message - is something that'd make sense to store in redux state, as the alternative would be passing state all over the place, e.g. an error prop bubbling up to your root component which renders the toast message. Using thunk is also a good idea when you're fetching/manipulating data relevant to the whole app, e.g. a list of things that appear in several places.
Use component state for storing state only relevant to the component. That is, if you're filling in a form, it makes sense to store the value of text inputs, checkboxes etc. in your component state (perhaps in conjunction with container and presentational components) as the values at this point aren't relevant to the rest of the application.

ReactJS local vs global state and implementing redux at a later time

So we are about two months in on a project. This is the first time I have ever managed code writers and not written the code myself. I've been reading their code for the last week. What was suppose to be a simple React app has turned into a spaghetti mess.
I understand: redux helps to manage global state. But should that mean that all buttons should map to a global "action?" This has seemed to create this entire mess of objects scattered throughout the entire app. I keep asking myself, why are we using global state for everything when local state could be used for 90% of the application. This is the kind of code that gives me heartburn:
let subitems = SidebarItems[state.type].sub_items;
Store.dispatch(SidebarSubItemHandler(item.action, subitems[0], null));
if(item.sub_items[subitems[0]].param) {
browserHistory.push(`${item.sub_items[subitems[0]].path}/${item.sub_items[subitems[0]].param}`);
} else {
browserHistory.push(item.sub_items[subitems[0]].path);
}
subItembuttons = Object.keys(this.props.subitems.sub_items).map(subitem => {
let subItem = this.props.subitems.sub_items[subitem];
return <li className={this.props.activeSubItem.action == subItem.action ? "bottom-bar-item active" : "bottom-bar-item"}
onClick={e => this.props.onClickSubItem(e, subItem)}
key={subItem.action} style={this.props.subitems.inlineStyles.mobileSubItemLI}>
{subItem.item}
</li>;
});
The application is littered with all kinds of objects like these that map to "action" objects. So at this point we are making the decision to scrap the entire project and restart from scratch, but without redux. Let's try to do as much as possible using local state only. When it comes time, and we need global state for something, ONLY implement it for that something, not every single action in the app. Does this make sense?
So I guess my question is: If we develop an app using local state and just fundamental React, will we be creating un-reversable problems that would prevent us from implementing redux on a per item basis?
Quoting from the relevant Redux FAQ entry at http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-only-redux-state:
Using local component state is fine. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.
Some common rules of thumb for determing what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
Per your specific question: if you use the "container component" pattern fairly consistently, it should be relatively straightforward to swap those "plain React" containers for Redux-connected containers down the line. See https://github.com/markerikson/react-redux-links/blob/master/react-component-patterns.md#component-categories for articles on the "container/presentational component" pattern.
Two other thoughts. First, I recently co-authored an article that discusses why you might want to use Redux in a React application.
Second: yeah, that code looks kinda ugly. I'm hoping those are at least three different snippets from different parts of the codebase, rather than one snippet, but that's rather hard to read. The repeated use of "sub_items" and "subitems" seems like a bit of a red flag, readability-wise.
It also doesn't look like it's following good Redux practices. For example, idiomatic Redux code almost never references the store directly. Instead, references to dispatch and getState are available via middleware, and thus can be used in action creators via redux-thunk and redux-saga. Connected components can also access dispatch.
Overall: you are absolutely welcome to use as much or as little Redux as you want, and as much or as little local component state as you want. I think the larger issue, though, is how well your team actually understands Redux, and how they're trying to use it.

designing redux state tree

I'm currently in the process of learning Redux, and I've more or less got the hang of the basic concepts. I understand how to work with actions and reducers and all that. What I am struggling with is understanding how to properly design a state tree. I get caught up on the particulars of what should/shouldn't be stored in the application state, when is it acceptable to use component state, the best way to handle state changes, etc.
Are there any good tutorials or blogs out there anyone can recommend for understanding the best practices of designing state?
There is a lot of differing opinion on this. Here is what I do.
Reducers - hold things that deal with my data model (normally anything that is in a database), that needs to be saved and used later or used across components
LocalState (react setState) - deals ui elements in a single component related to user input and interaction
So if i were modeling a response to this question. Redux store would have
store = {
session: { token: 'randomUid' }
user: { name: 'Austio' }
question: { id: 37288070 }
}
When I select the text box to enter values in to create an answer to this question is would handleInput from this box, which would setState of the answerText.
When is handleSubmit for the form, i would dispatch out based on success something like NEW_ANSWER with the questionId and the answer so that i could store it in the store to be used whereever i need it.
My best advice is to just start programming stuff, it is very difficult to find the edges of your preferences with using redux/react without that.
I'd highly recommend checking out Dan Abramov's(creator of Redux) tutorial on egghead.io
https://egghead.io/courses/getting-started-with-redux
He takes you through building a simple todo application, but really emphasizes on the best state building practices throughout the course.

Categories

Resources