[go: up one dir, main page]

0% found this document useful (0 votes)
74 views10 pages

How To Build A Redux-Powered React App

The document provides instructions for setting up a React app with Redux. It describes how to: 1) Create a React app using create-react-app, 2) Install Redux and react-redux libraries, 3) Create a reducer to manage state, 4) Build the store and connect it to the React app, 5) Create actions, 6) Build a sample UI component to display state, 7) Access the store's state from the component using the useSelector hook, and 8) Dispatch actions from the component using the useDispatch hook.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views10 pages

How To Build A Redux-Powered React App

The document provides instructions for setting up a React app with Redux. It describes how to: 1) Create a React app using create-react-app, 2) Install Redux and react-redux libraries, 3) Create a reducer to manage state, 4) Build the store and connect it to the React app, 5) Create actions, 6) Build a sample UI component to display state, 7) Access the store's state from the component using the useSelector hook, and 8) Dispatch actions from the component using the useDispatch hook.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Initial Code Setup

Let's get everything we need setup for our project. Just follow these steps and you'll
be up and running in no time.

1. Create a React app with the create-react-app


command

npx create-react-app react-app-with-redux

2. Go to the newly created folder


Just type this command to navigate to the new folder:

cd react-app-with-redux

3. Install Redux and the react-redux libraries


You can install Redux and react-redux like this:

npm install redux react-redux

4. Run the application


You can run your new app with the following command:

npm start
How to Build the Main App
5. How to create the Reducer
To create a reducer, �rst create a folder inside src named actionTypes . Then
create a �le inside it named actionTypes.js . This �le will contain all the actions the
application will be dealing with.

Add the following lines in actionTypes.js :

export const ADD_ITEM = "ADD_ITEM";


export const DELETE_ITEM = "DELETE_ITEM";

Since our app will have the functionality of adding and deleting items, we need the
above two action types.

Next create a folder inside the src called reducers and create a new �le in it
named cartReducer.js . This �le will contain all the reducer logic related to the
cart component.

Note: We will create the view/ UI in step 8, so hold on for that.

Add the following lines in cartReducer.js :

import { ADD_ITEM, DELETE_ITEM } from "../actionTypes/actionTypes";

const initialState = {
numOfItems: 0,
};

export default const cartReducer = (state = initialState, action) => {


switch (action.type) {
case ADD_ITEM:
return {
...state,
numOfItems: state.numOfItems + 1,
};

case DELETE_ITEM:
return {
...state,
numOfItems: state.numOfItems - 1,
};
default:
return state;
}
};

As we discussed it in my previous tutorial, we created an initial state for the app


and assigned it to the default parameter of state in the cartReducer function.

This function switches on the type of action dispatched. Then depending on


whichever case matches with the action type, it makes necessary changes in the
state and returns a fresh new instance of the updated state.

If none of the action types matche, then the state is returned as it is.

Finally we make a default export of the cakeReducer function to use it in the store
creation process.

6. How to create the store and provide it to the app


Create a �le inside src with the name store.js and create the store using this
command:

const store = createStore()

Add the following lines in store.js :

import { createStore } from "redux";


import { cartReducer } from "./reducers/cartReducer";

const store = createStore(cartReducer);

export default store;

Now it's time to provide this store to the App component. For this we'll use the
<Provider> tag that we get from the react-redux library.

We wrap the whole App component inside the <Provider> tag using the following
syntax:
// rest of the code ...

<Provider store={store}>
<div>App Component</div>
// child components of App/ other logic
</Provider>

// rest of the code ...

By wrapping the App component inside the <Provider> tag, all the children
component of App will get access of the store . You can read my previous article on
What is Redux? Store, Actions, and Reducers Explained for Beginners to know
more.

Continuing with App.js , add the following lines to the �le:

import "./App.css";
import { Provider } from "react-redux";
import store from "./store";

function App() {
return (
<Provider store={store}>
<div>App Component</div>
</Provider>
);
}

export default App;

7. Create the Actions


Now create a folder inside src called actions and create a �le inside it called
cartAction.js . Here we will add all the actions to be dispatched on some user
interactions.

Add the following lines in the cartAction.js :

import { ADD_ITEM, DELETE_ITEM } from "../actionTypes/actionTypes";

const addItem = () => {


return {
type: ADD_ITEM,
};
};

const deleteItem = () => {


return {
type: DELETE_ITEM,
};
};

export { addItem, deleteItem };

In the above code we created two action creators (pure JS functions that returns
action object) called addItem() and deleteItem() . Both the action creators
return action objects with a speci�c type .

Note: Each action object must have a unique type value. Along with it, any
additional data passed with the action object is optional and will depend on the
logic used for updating the state

8. How to create the view/UI


Now that we have created all the required entities such as the store, actions, and
Reducers, it's time to create the UI elements.

Create a component folder inside src and a Cart.js �le inside it. Add the
following lines inside Cart.js :

import React from "react";

const Cart = () => {


return (
<div className="cart">
<h2>Number of items in Cart:</h2>
<button className="green">Add Item to Cart</button>
<button className="red">Remove Item from Cart</button>
</div>
);
};

export default Cart;

Add this Cart component in the App.js �le:

import "./App.css";
import { Provider } from "react-redux";
import store from "./store";
import Cart from "./component/Cart";

function App() {
return (
<Provider store={store}>
<Cart />
</Provider>
);
}

export default App;

Just to make it a bit presentable, I have added a bit of basic styling in App.css as
follows:

button {
margin: 10px;
font-size: 16px;
letter-spacing: 2px;
font-weight: 400;
color: #fff;
padding: 23px 50px;
text-align: center;
display: inline-block;
text-decoration: none;
border: 0px;
cursor: pointer;
}
.green {
background-color: rgb(6, 172, 0);
}
.red {
background-color: rgb(221, 52, 66);
}
.red:disabled {
background-color: rgb(193, 191, 191);
cursor: not-allowed;
}
.cart {
text-align: center;
}

This is how the UI looks as of now:


9. How to read and access the store using the
useSelector hook
useSelector is a hook provided by the react-redux library that helps us read the
store and its content(s).

Import the hook from react-redux and use the following syntax to read the store
with useSelector hook:

import { useSelector } from "react-redux";


// rest of the code
const state = useSelector((state) => state);

// rest of the code

After adding the useSelector hook, your Cart.js �le will look something like this:

import React from "react";


import { useSelector } from "react-redux";

const Cart = () => {


const state = useSelector((state) => state);
console.log("store", state);
return (
<div className="cart">
<h2>Number of items in Cart:</h2>
<button className="green">Add Item to Cart</button>
<button className="red">Remove Item from Cart</button>
</div>
);
};

export default Cart;

Console logging the state will give us the initial state that we set in the reducer �le
in step 5.
10. How to dispatch an action on button click with
the useDispatch hook
The react-redux library gives us another hook called the useDispatch hook. It helps
us dispatch the actions or action creators which in turn return actions. The syntax is
as follows:

const dispatch = useDispatch();

dispatch(actionObject or calling the action creator);

Thus adding a dispatcher into our Cart.js will �nally make the �le look something
like this:

import React from "react";


import { useSelector, useDispatch } from "react-redux";
import { addItem, deleteItem } from "../actions/cartAction";

const Cart = () => {


const state = useSelector((state) => state);
const dispatch = useDispatch();
return (
<div className="cart">
<h2>Number of items in Cart: {state.numOfItems}</h2>
<button
onClick={() => {
dispatch(addItem());
}}
>
Add Item to Cart
</button>
<button
disabled={state.numOfItems > 0 ? false : true}
onClick={() => {
dispatch(deleteItem());
}}
>
Remove Item to Cart
</button>
</div>
);
};

export default Cart;

Note how on click of the Add Item to Cart button, we dispatch the action creator
addItem() that we created in step no. 7.

Similarly on click on the Remove Item from Cart button, we dispatch the action
creator with deleteItem() .

The state variable stores the state of the app, which is basically an object with a
key numOfItems . So state.numOfItems gives us the current number of items value
in the store.

We display this information in the view in the line <h2>Number of items in Cart:
{state.numOfItems}</h2> .

To dig a bit deeper, when a user clicks the Add Item to Cart button, it dispatches the
addItem() action creator. This, in turn, returns an action object with type type:
ADD_ITEM .

As mentioned in my previous tutorial, when an action is dispatched, all the reducers


become active.

Currently in this example we have only one reducer – cartReducer . So it becomes


active and listens to the action dispatched.

As shown in step 5, the reducer takes the state and the action as input, switches on
the action type and returns the fresh new instance of the updated state.

In this example, when the action with type: ADD_ITEM matches the �rst switch
case, it �rst makes a copy of the entire state using the spread operator ...state .
Then it makes the necessary update – which in the case of adding items is
numOfItems: state.numOfItems + 1 (that is increasing the numOfItems by 1).

Similarly, using the same logic, on clicking on the Remove Item from Cart button, an
action with type type: DELETE_ITEM is dispatched which goes and decreases the
numOfItems by 1.

Here is the demo of the working app:

Notice how we were able to control the behavior of the Remove Item from Cart
button based on the value of numOfItems in the Redux store. As a negative number
of items does not makes sense, we disabled the Remove Item from Cart button if
state.numOfItems <= 0 .

This way we are able to prevent the user from decreasing the number of items in
the cart if its already 0.

This was a basic example to show you how we can control the behavior of various
DOM elements based on the internal state of the app.

And there you go! We just �nished setting up our �rst Redux-powered React
application. Now you can go ahead and create various other components based on
your requirements and share a common global state among them.

You might also like