Redux Structures Redefined

While developing a React Application, Redux is an integral part which comes into play at least at an intermediate level and is considered to be an essential part of the development process. Without going into much detail of what Redux is, let’s go on with a brief introduction of what Redux Structure is and what all components are needed to understand its architecture.

  • State:

State in redux controls the complete behaviour of components within react native. These are mutable i.e. change over time. An example for the same could be updating a text on the click of a button. In this case, the text updation will happen by a change in-state only.

import React, { useState } from 'react';
import { Text, View, Button } from 'react-native';
function App() {
// Declare a new state variable, which we'll call "user"
const [user, setUser] = useState(‘John’);
return (
<View>
<Text>Welcome {name} !</Text>
<Button onPress={() => setUser(‘Peter’)}>
title = {“Update”}
</Button>
</View>
);
}
  • Actions:

As already clear with the name, in general terms, it can be considered as an act to bring about a change.

Here, An action is a plain JavaScript object (notice how we don’t introduce any magic?) that describes what happened. An example of action can be a click on the button within the screen. Actions send data from let’s say API calls to the store. Those actions have a property called “type” that describes the type of action and also the data to be sent to the store.

A code snippet for the same can be:

function loginAction(form) {
return {
type: LOGIN_SUBMIT,
payload: {username: ‘John’, password: ‘12345678’}
}
}
  • Reducers:

It can be considered as a function that binds together a state and an action of a component and returns back the next state i.e. the updated state for the same component.

Overall Working:

Step 1: An action at first occurs within a component, such as someone trying to log in, list some data, see the details of a component, or even delete a component, etc.
Step 2: Which then calls the action and action type
Step 3: That then calls the particular reducer that will update or modify the state
Step 4: And once the state is changed, the view is rerendered

Defining the various Architecture patterns:

Now that we have a brief description of components which will be used in Redux Structure. Let’s go ahead and get started with our Redux Structure.

1. By Type:

In this method, all the four components in use are created in different files as shown:

This is considered as the traditional method now as if any functionality needs to be changed, the changes have to be done in all the four files.
You’d have to edit the constants in one file, then edit the reducer in 2nd, then edit the actions in 3rd one, and finally, edit the action creators in yet another.

This means even for adding a small feature, might require adding and editing different files which is quite cumbersome and time-consuming! 😥

Let’s take an example for this approach:

Create a directory for the constants within redux: src/redux/constants

Create a new action-types.js file within that folder. In that file:

// src/redux/constants/action-types.js
...
export const LOGIN_SUBMIT = “LOGIN_SUBMIT”;

Then open up src/redux/actions/index.js and update the action to use action types:

// src/redux/actions/loginAction.js
import { LOGIN_SUBMIT} from “../constants/action-types”;
export const loginsubmit = data => ({type: LOGIN_SUBMIT, payload: data });

2. By Feature:

In the example, let’s consider a feature called “Login”. The redux structure is shown below where all the files related to a particular feature are kept in a folder. As can be seen, the files are still the same as the above approach but now encapsulated within a folder. Summarizing –

  1. encapsulating a component (the container)
  2. its reducer
  3. and its behavior (the actions) into a single folder like:
//src/login

- login (folder)
- loginComponent.js (screen)
- loginReducer.js
- loginActions.js
- loginConstants.js

3. By Ducks Method:

Ducks is essentially a method where reducers, actions and action types all are bundled into the same file irrespective of the feature.

This method basically resolves the issue of hopping back and forth within the files when organized by the above 2 methods. With this approach we can combine all in one package and create modules. So let’s go ahead and refractor the above code.

So we created a basic functionality of login above and now we’ll need to move action_types, actions and reducers all in a single file rather than 3-4 different files.

Step 1: Create a directory for the Ducks within redux:
src/redux/ducks

Step 2: Create a file index.js within that folder

Step 3: Take action_types from the constants folder and put it into new ducks file i.e. in index.js

// src/redux/ducks/index.js
...

export const actionTypes = {
loginSubmit: {
LOGIN_SUBMIT = "LOGIN_SUBMIT"
}
};

Step 4: Now delete the entire constants folder created earlier.

Step 5: Next take the actions file created earlier and put it under ducks file.

// src/redux/ducks/index.js
…

export const actions = {
loginSubmit = data => ({type: LOGIN_SUBMIT, payload: data })
};

Step 6: Continue and let’s delete the actions file now!

Step 7: Lastly get hold of the reducer file and begin the change! In the ducks file add:

// src/redux/ducks/index.js
…

export const rootReducer = (state = initialState, action) => {
switch (action.type) {
case LOGIN_SUBMIT :
return {...state, loginResponse: [...state.loginResponse, action.payload] };
default:
return state;
}
};

Step 8: Now, of course, let’s delete the reducer folder!

Hooray! We’ve just created a modified Ducks file! Let’s take a look.

The above file works the same way but now has been reformed for a clean and robust look with an optimized management. Moreover, it’s pretty easy to create!

As far as structure is considered every developer has their own methodology. Choose the one you like and start. There might be plenty of methods available like this. Hope this article helps to avoid mess and restructure yourself along with the code.

Keep Spreading Knowledge and Happy Coding!! 🙂🙂

We Keep Sharing Tips And Learnings On Growth And Technology. Join Our Popular Newsletter That Goes Out Once In 2 Weeks

Shivangi

Tech Expert

Shivangi is a React Native developer with over 3.5+ work of experience with good knowledge in Android, React Native applications. She is proficient in requirement analysis, application development, and maintenance, functional studies. She is dedicated to continuously developing, implementing, and adopting new technologies to maximize development efficiency and produce innovative applications. she is a self-motivated, quick learner and she loves to resolve technical issues.

Get in touch for a detailed discussion.

What’s on your mind? Tell us a little bit about yourself and your question, and we will be in touch with you within 12 hours

Free eBook on Telemedicine Platform Development: All About Telemedicine

Download Free eBook Now!