State management in ReactJS using Redux library
Tags: redux, reactnative, react, javascript
Published: 2019-11-28 09:07:58

<img src="https://redux.js.org/img/redux.svg"/>
There are several options for managing state inside ReactJs projects. You may have heard about libraries like <a href="https://redux.js.org/">Redux</a>, <a href="https://reactjs.org/docs/context.html">Context API</a>, <a href="https://github.com/mobxjs/mobx">Mobx</a> and <a href="https://github.com/jamiebuilds/unstated#introducing-unstated">Unstated</a>. In this article we are going to describe more about state management and Redux. 

<b>My story:</b>
When I started working with React Native, as a native mobile developer, I found states scary and weird. In Java, we have <a href="https://developer.android.com/reference/android/content/Intent">Intents</a> and <a href="https://developer.android.com/reference/android/app/Application.html">Application</a> class to send data between pages and store global variables. But none of them exists in React Native. Plus, In my first app, I didn't know why should we use a third-party to manage the application state while we have built-in state API. At that moment I just followed some tutorials about Redux and its implementation in React projects. Now after developing several applications with React and state managers, I found how state management can be useful to make our project structure better, project lines of code lower and your project more understandable for other developers. The thing is in big-scale projects, using state managers is a must! 
<i>
I know that at first, maybe it will be wired and scary for you if you don't have a strong javascript understanding yet, but try to use it like me and don't blame yourself if you could not understand it deeply. Even today that I am writing this blog post, state management, and Redux is not easy peasy for me but I have to use it. I hope this article helps you to understand Redux better. 
</i>
<b>Redux</b>
Redux is the first library that solved state management in React. It is so popular among React developers. In Redux we have several key elements:

<b>1- Store:</b> all our data will keep here.
<b>2- Actions:</b> they let us to send our data to Redux. Technically they are simple javascript objects that must have a type and can include several key-value data.

```javascript
{
   type:"LOGIN_SUCCESS",
   token:"user token here ..."
}
```
 We can also have <b>action creators</b> for ease:
```javascript
function loginSuccess(token){
    return {
        type:"LOGIN_SUCCESS",
        token
    }
}
function logout(){
    return {
        type:"LOGOUT"
    }
}
```
<b>3- Dispatch:</b> it is a redux API that runs our actions. In fact, in order to save our data, we should run our actions using dispatch API.
```javascript
store.dispatch(loginSuccess()); //dispatch api only accept javascript objects
```
<b>4- Reducers:</b> they are just pure javascript functions that accept actions as their argument and decide what to save in store when an action is sent to them.
```javascript
const defaultState={
    auth: false,
    token: null
}

export default function users (state=defaultState, action){

    switch(action.type){

        case "LOGIN_SUCCESS":
            return {
                ...state,
                auth: true,
                token: action.token
            }
        case "LOGOUT":

            return {
                ...state,
                auth: false,
                token: null
            }

        default: 
            return state;
    }

}


```
** <b>Keep in mind that you must not have any side effect operation inside your reducer function. For example, you cannot fetch data from your API inside your reducer function.</b> If you are looking for more detail about <a href="https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/">PURE functions</a> in javascript, please check this blog post.

** <b>Writing only one general reducer?</b> Redux accepts only one reducer but it is a bad practice to have a big general reducer function. It is better to write reducers based on their functionalities. For instance, we can have a reducer for users' stuff and one another for notifications and so on. At the end of the article, you see how we can use combineReducer API to merge all reducers to one.


<b>Connecting your app to Redux</b>
The next part is installing the Redux library and connecting your app to it. 
```javascript
npm install --save redux react-redux
```
After installing libraries open index.js file. At first, it should look like it:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


```
We need to change it to:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {createStore,combineReducers} from 'redux' //1
import users from './redux/users'//2
import {Provider} from 'react-redux' //3

const reducers=combineReducers({notifications}) //4
const store=createStore(reducers); //5


ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root')); {/* 6 */}

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

```

<b> Line 1: </b> importing createStore and combineReducers API's from redux package.
<b> Line 2: </b> importing our reducers. remember we have only one reducer but you can have as many as you need.
<b> Line 3: </b> importing Provider component. The provider component lets us connect our app to our store.
<b> Line 4: </b> combining all reducers to one reducer using combineReducer API. In the case of having several reducers we should write like this:
```javascript

const reducers=combineReducers({users,notifications,test1,test2})

```

<b> Line 5: </b> Creating our store based on main reducer.
<b> Line 6: </b> Putting <App/> component inside <Provider>.


<b>Read and write state</b>
Now everything is ready and we can read and write our states. You only need to connect your component to the Redux to complete your job.
```javascript
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from 'react-redux';
import {login,logout} from './redux/users';

class App extends React.Component{


  componentDidMount(){
    setTimeout(() => {
      this.props.login("token here...") //1
    }, 1000);
  
    setTimeout(() => {
      this.props.logout(); //2
    }, 5000);

  }
  render() {
  
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            USER TOKEN :
          </p>

          {this.props.users.auth && <p>{this.props.users.token}</p>} {/* 3 */}

        </header>
      </div>
    );
  }
}

function mapStateToProps(state){
  return{
    users: state.users
  }
}

const mapDispatchToProps={login,logout}

export default connect(mapStateToProps,mapDispatchToProps)(App); //4
```

<b> Line 1 & 2: </b> here we are calling our actions. Redux will send our actions to dispatch API and then passes it to our reducer...

<b> Line 3: </b> reading state from redux. Our component will be re-rendered when the user data changes.
<b> Line 4: </b> connecting our App component and then export it.

<b>Github repository of this tutorial</b>
Developers like to learn things through code examples. If you are looking for a working demo, you can check out my <a href="https://github.com/mdeveloper20/reactReminder/tree/normal-redux">React Redux Github branch here<a/>. It is a basic react application that I implemented Redux in it. The reason why I made this repository is that it's gonna remind me implementation of all the useful libraries in Redux instead of looking on the internet for it. That is why I name it <a href="https://github.com/mdeveloper20/reactReminder">React Reminder</a>. You can use this repo or you can have yours.

<b>Summery</b>
Redux is one of the useful libraries to manage your React application state. There are other options for you to do state management in your application like Context API. It is worth to take a look at other options before using Redux. In this article, we talked about how important state management is and showed how you can implement one of them in your projects step by step. 
For more information about Redux, you can read its <a href="https://redux.js.org">official documentation</a>. If you are curious to learn more about Redux, I recommend you take a look at it's middlewares like <a href="https://github.com/reduxjs/redux-thunk">Redux-Thunk</a> and 
 specially <a href="https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html">Redux-Saga</a>. 

{% youtube 6sOqeRB39Eg%}