Skip to main content

Create a React Redux App with Visual Studio 2017 and ASP.NET Core 2.2

Redux is a predictable state container for JavaScript apps. It’s a mechanism to store and share the data on the client side within the application. Redux is generally used in a combination of React, but it’s not tied to React. Earlier I posted about creating a React App with Visual Studio 2017 and ASP.NET Core 2.2 and in the same post, I mentioned that there are 2 pre-defined templates for creating a React application. The React.js template creates a react application, where the React.js And Redux template has Redux configured for you. In this post, find out how to create a React Redux App with Visual Studio 2017 and ASP.NET Core 2.2.

What is Redux anyway?

State management is one of the most integral part of any software as it increases the website performance by reducing the response time to get the data. With the new client-side frameworks, you can now implement client-side state management and Redux is one of the possible options. From the official documentation,

Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

You can use Redux together with React, or with any other view library.

Redux is a tiny library (only 2KB, including dependencies) which helps you to maintain the state on the client-side. Below are some advantages of Redux,

  • Lightweight
  • It uses “pure” reducer functions makes logic easier to write, understand and test.
  • Supports hot reloading and time travel debugging to go backward to a previous point in your state.
  • The Redux store is a single immutable object. That results in safer data handling as it allows no modifications once added. You always replace the existing state with a new state.

There are 3 main components of Redux which are Actions, Reducers, and Stores. Action defines the user interaction (button click), Reducers takes the previous state of the application and an action and then returns a new state and Store is the object that holds the application state and provides helper methods to access the state, dispatch actions and register listeners.

React Redux App with Visual Studio 2017 and ASP.NET Core 2.2

If you want to learn React the right way, I want to personally recommend FullStack React as the single-best resource out there. It is the up-to-date, in-depth, complete guide to React and friends. You can get a copy here.

Before we begin, please do the following installation (ignore if already done).

Open Visual Studio 2017, hit Ctrl+Shift+N and select the ASP.NET Core Web Application (.NET Core) project type from the templates. When you click Ok, you will get the following prompt. Select ASP.NET Core 2.2 and choose the React template.

Create a React Redux App with Visual Studio 2017 and ASP.NET Core 2.2

Hit “OK” to create the application. Let’s take a close look at the application structure and how ASP.NET Core is running this react app.

React Application Structure

Below is a screenshot of the react redux application structure.

React With Redux Application Structure

You can see the store folder created inside the React app. This store folder is where the Redux store is configured. The sample react app is having 3 files in it.

  • configureStore.js: You can put the code to create Redux store in your index.js file, but over the period it becomes hard to maintain, as the code is no longer organised. And also most apps use more than one middleware, and each middleware often requires some initial setup. The solution to this problem is to create a new configureStore function which encapsulates the redux store creation logic, which can be placed in its own file to ease extensibility. So, all your logic related to configuring the store – including importing reducers, middleware, and enhancers – is handled in a dedicated file.
  • Counter.js: The sample react application has 2 components and one of them is the counter. The component has a button to increment a value, and this value is stored in a Redux store. Below is the code of the Counter.js.
    const incrementCountType = 'INCREMENT_COUNT';
    const decrementCountType = 'DECREMENT_COUNT';
    const initialState = { count: 0 };
    
    export const actionCreators = {
      increment: () => ({ type: incrementCountType }),
      decrement: () => ({ type: decrementCountType })
    };
    
    export const reducer = (state, action) => {
      state = state || initialState;
    
      if (action.type === incrementCountType) {
        return { ...state, count: state.count + 1 };
      }
    
      if (action.type === decrementCountType) {
        return { ...state, count: state.count - 1 };
      }
    
      return state;
    };
    

    From the Counter component (present in components folder), the react container which gives the component props the ability to interact with the state. Don’t confuse yourself between Component and Container. They’re both components. Containers receive Redux state updates and dispatch actions, and but don’t render DOM. They just dispatch to props for the presentational component. The following code in Counter.js component class is an example of a react container.

    export default connect(
      state => state.counter,
      dispatch => bindActionCreators(actionCreators, dispatch)
    )(Counter);
    
  • WeatherForcast.js: The other react component in this sample app fetches the data from ASP.NET Core Web API and displays the same. The following highlight code first checks the Redux store to see if the data is present for the request or not. If yes, then it doesn’t call to the server to get the data.
    export const actionCreators = {
      requestWeatherForecasts: startDateIndex => async (dispatch, getState) => {    
        if (startDateIndex === getState().weatherForecasts.startDateIndex) {
          // Don't issue a duplicate request (we already have or are loading the requested data)
          return;
        }
    
        dispatch({ type: requestWeatherForecastsType, startDateIndex });
    
        const url = `api/SampleData/WeatherForecasts?startDateIndex=${startDateIndex}`;
        const response = await fetch(url);
        const forecasts = await response.json();
    
        dispatch({ type: receiveWeatherForecastsType, startDateIndex, forecasts });
      }
    };
    

That’s it. The steps for publishing and deploying this app in IIS is same as mentioned in this post.

Recommended Reading:

Learn React the right way via FullStack React. It is the up-to-date, in-depth, complete guide to React and friends. You can get a copy here.

Summary

Redux is a state management tool for JavaScript applications and it’s generally used with React, but it’s not tied to React. For complex react application, it becomes hard to manage state object when react app grows to multiple components. Redux solves this problem and all react components can talk to the store to get the state, instead of transferring the state between component. In this post, we briefly touched the basics of Redux and walk-through of the sample react redux app created with Visual Studio 2017 and ASP.NET Core.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *