Your Privacy

This site uses cookies to enhance your browsing experience and deliver personalized content. By continuing to use this site, you consent to our use of cookies.
COOKIE POLICY

Understanding React-Redux

Understanding React-Redux
Back to insights

When developing JavaScript-based web applications a common framework choice is React. React is Facebook’s user interface library that provides support for component-based development. React applications often use Redux as a state container imported via the React-Redux library.

Why use Redux in a React application?

React encourages component-based website development. For example, a simple bulleted list might decompose into two components – a parent <ul /> and a child <li />. In React, the state is application data. State propagates one-way through the application. Referring to the previous example, if another component elsewhere on the page needed access to the state inside of the <li />, without redux, the state would need to be hoisted to an ancestor of the two components in question and passed down.

Without Redux

There is a problem:

<App>

<div>

<ul>

<li /> <!-- state stored in this component -->

</ul>

<div> <!-- but this component needs access to the state in the <li /> -->

</div>

</App>

Fixing the problem by hoisting state:

<App>

<div> <!-- move the state from <li /> to here -->

<ul>

<li /> <!-- Pass the state down to here -->

</ul>

<div> <!-- Pass the state down to here -->

</div>

</App>

This issue becomes a major problem at scale. Over time, as more components require access to each other’s state, the immediate solution is to hoist state to the highest component in the entire application and pass it down to necessary child components. Redux solves this problem by providing a single state container that all components can access without the need for hoisting state. The following section will explain how to use Redux with React.

How to Use Redux with React

To see this example in action:

Follow the link here and install Node.

  1. Clone the code from the following link: https://github.com/chalb500/spooky-monsters
  2. Navigate to the root folder of the locally cloned code
  3. Enter ‘npm install’ into your terminal
  4. Enter ‘npm start’ into your terminal

Action Creators

Navigate to the actions folder in the solution and open Monsters.js. Inside of this file is a function called “setMonsters” that accepts some monsters and has a “type” of “SET_MONSTERS”.

export const SET_MONSTERS = 'SET_MONSTERS'

export function setMonsters(monsters) {

return {

type: SET_MONSTERS,

monsters

}

} 

Reducers

Navigate to the reducers folder in the solution and open Monsters.js. Inside of this file is a reducer called “monsters” that accepts some state and an action. The action that will apply to this reducer is “SET_MONSTERS” from the action creator above. When “SET_MONSTERS” is triggered, it will create a new copy of the state that includes the monsters that were passed into the action creator above.

import { SET_MONSTERS } from '../actions/monsters'

export default function monsters (state = {}, action) {

switch (action.type) {

case SET_MONSTERS :

return {

...state,

...action.monsters

}

default :

return state

}

}

Connect React Components to Redux

Go to the src folder and open index.js. Inside of here is some boilerplate code where a new redux store is created and the reducers are passed to the store. A Provider component wraps the application and provides downstream components the ability to connect to the redux store.

<Provider store={store}>

<App />

</Provider>,

Navigate to the components folder and open MonsterList.js. The “mapStateToProps” is boilerplate code for accessing data within the store. This boilerplate code provides access to the monsters.

function mapStateToProps({monsters}) {

return {

monsters

}

}

The code at the bottom of this file passes the “mapStateToProps” definition to Redux and instructs Redux to connect the MonsterList to the Redux store.

export default connect(mapStateToProps)(MonsterList);

Initialize the Store

Inside of the same component folder, open up App.js. Inside of the lifecycle method, the store is initialized.

componentDidMount() {

const { dispatch } = this.props

//Initializing the application data

dispatch(setFavorite(FAVORITE))

dispatch(setMonsters(MONSTERS))

}

When you are looking to enhance your digital presence, we can help. UDig has an experienced team of React developers that can leverage the latest technologies to provide cutting-edge web application solutions.

About The Author

Cody Halbleib is a Senior Consultant on the Software team. His family is his partner, Jamie, and his Border Collie mix, Walter.

Digging In

  • Digital Products

    Unlocking Business Potential: The Power of Custom Application Development

    Like any savvy business leader, you’re likely always on the lookout for tools to give your company a competitive edge. And in doing so, you’ve undoubtedly considered investing in custom application development. But the question is, how do you ensure that such a major investment in a custom web application development provides a strong return on […]

  • Digital Products

    Mastering Legacy Application Modernization: Strategies for Success

    The ironic truth of the business world is that change is the only constant. But this means that failing to keep pace with the competition and its technologies will only end with you falling behind. That’s where legacy application modernization enters the fold. When you modernize legacy applications, your team gains access to new features […]

  • Digital Products

    CTO Confessions Podcast

    In this episode of CTO Confessions, Rob Phillips, the Vice President of Software Engineering at UDig, digs into his journey from a passionate technologist in his youth to a seasoned leader in the tech industry. He shares valuable lessons on transitioning to senior leadership, the importance of understanding and articulating company problems, and the art of empowering teams for high performance.

  • Digital Products

    Navigating the Challenges of On Premise to Cloud Migration

    In today’s rapidly evolving technological landscape, the shift from on premise solutions to cloud-based infrastructure has become a pivotal transformation for organizations seeking to modernize their IT operations. This transition holds the promise of increased agility, cost savings, and enhanced scalability. However, it is not without its set of formidable challenges that organizations must navigate. […]

  • Digital Products

    The Power of Transferrable Skills in Tech Projects

    Every project has its own unique elements that require flexibility to be effective and achieve success. This often requires picking up new pieces of a tech stack, learning a new programming language, or a new project methodology. Fortunately, there are also many transferrable skills that carry over from one project to the next. In my […]

  • Digital Products

    The Four Pillars of Effective Digital Product Development

    In 2020 alone, approximately two billion consumers purchased at least one digital product. From software licenses to mobile apps and tech tools, consumers are becoming increasingly active in the digital product market, a trend that has naturally spurred brands across a wide range of industries to reevaluate their digital product design and development process workflows. […]