Now you wonder how does Redux know what to do when we “order him” to do specific task, how does he know how to process that task/action?!

Well we do that using “Reducers”. Reducers are plain Javascript Functions, which are used to handle the Actions, there can be minimum one Reducer, but your app can have as many Reducers as you want!

A Reducer Function looks like this:

Redux Reducer Function

So Redux developers usually use the switch statement to tell redux what to do based on the action the reducer receives, but of course you could do something like this:

Redux Reducer Function

But of course your reducer would hold more actions, and having that many IF/ELSE statements is a bit untidy, so I recommend using the switch statement.

Also as you may have noticed the reducer has 2 arguments, the first argument is the current state and the second argument is the action you have dispatched in the previous example.

So the reducer passes down the Current State and the Action you have dispatched and the only thing Redux wants from you is to Return a New Immutable State.

An Immutable State means basically a clone of the current state with the new changes done.

The 3 dots in the return statement in the reducer function means:

create a new copy from the state object but the new copy needs to hold the someData as property of that state object

so you can’t do:

Updating Redux State the wrong way

Because you are directly changing the current state object, you need to create a new clone of it and change that new clone, so you must either use the 3 dot operator (ES6 Feature, if you don’t use react you need to use polyfill) or use Object.assign (same as 3 dot operator, also needs polyfill to work), or you could just do:

Alternative way of creating immutable state in Redux

But I more like the 3 dot operator as it has cleaner syntax.

Note the Reducer Function MUST return a state, if the action the reducer received doesn’t match any of the cases in the switch statement, then you can just return the same state, as I did above.

Lastly you need to “Create the actual Store” which will be used to manage the state.

You Can create the Store by calling the createStore function from the redux library and passing the reducer function as statement:

Creating Store in Redux

Now you can subscribe/unsubscribe to the store, or pass it to a Provider if you are using React/React Native Library

So Basically Redux works like this:

Dispatch an Action

2. Define a Reducer Function

3. Handle the Action Dispatched in the Reducer and Return a New Immutable State.

Hope you liked my first Medium post, and I hope you got the idea on how Redux works, for any questions leave a comment bellow and I will answer them As soon as possible.

NOTE: This Post explains you how Redux Works, it doesn’t provide a full example. If you want a tutorial on how to use Redux with React leave a comment bellow.

Regards,

Jack. :)