Reputation: 496
I am thinking about learning reactjs recently and I hope if someone could help me to understand the circumstances to use redux, as I am confused by its complicated logic.
First, I have used angular2+ for a while, and so I am also trying to grab the idea from the what I have already know.
I have seen many examples of redux but I don't understand the benefit to use actions and dispatch.
What is the benefit of using redux store using actions and reducers instead of just use class and subject like this?
class Store{
subject = new BehaviorSubject(0);
get value(){
return this.subject.getValue();
}
inc(){
this.subject.next(this.subject.value+1);
}
dec(){
this.subject.next(this.subject.value-1);
}
clear(){
this.subject.next(0);
}
}
class Demo extends React.Component<{}, {}>{
store = new Store();
componentWillMount(){
this.store.subject.subscribe(_ => this.forceUpdate())
}
render(){
const value = this.store.value;
const { inc, dec, clear } = this.store;
const store = this.store;
return (
<div>
<span>{`current value is ${value}`}</span>
<button onClick={inc.bind(store)}>INC</button>
<button onClick={dec.bind(store)}>DEC</button>
<button onClick={clear.bind(store)}>CLEAR</button>
</div>
);
}
}
Upvotes: 2
Views: 1114
Reputation: 67469
@Dmitry Sokurenko's answer is good. For more info, see Dan Abramov's posts on You Might Not Need Redux and The Case for Flux, as well as the Redux FAQ on "when should I use Redux?". Also, while you're not using React, you might also be interested in an article I co-wrote about the benefits of using Redux in a React app.
Upvotes: 0
Reputation: 6132
The benefits of dispatching actions over traditional method calling:
Logging—as all the actions can be easily logged, you always see what's going on in the app. For larger apps that's the killer feature for me.
Preprocessing—you can use redux middlewares to perform all kinds of fancy preprocessing of your actions—most typical is automating xhr requests in some way.
As actions are serializable implementing features like "undo" is much easier, while that's not necessary too often.
About the reducers—reducers happen to be the cleanest way to update immutable state. So it's not so much about the reducers as about mutable vs immutable store state, and that's quite a religious question. I would say that given enough discipline mutable state works as well as the immutable one.
About the preprocessing—basically you can have a piece of code which looks on all the actions happening in the system and doing something if an action matches some criteria.
For example:
{ url, params }
properties will result into a request to the backend API specified by the { url }
and converted into new actions which would have the { responseJson }
property instead of the url & params{ debounce }
property will be debounced, so if you issue a dozen of such actions in a row only the last one will be actually processed.{ alert }
property would show a small toast alert to the user.Upvotes: 1