Connecting your React app to Redux

Alrighty, ladies, gents, and non-binary folk! You may recall from my post last week that I mentioned creating a family website for my dad utilizing their personal weather station’s (pws) data.

This week I’m working on connecting my app to Redux so that it’s all nice and tidy and organized, especially since I will eventually be fetching data from at least 3 pws’s.

And I don’t know about you but man this one for some reason is a hard one for me to remember! I thought that it might be helpful to create a step-by-step guide to get this all set up and working, and so maybe it wouldn’t be so ‘difficult’ in the future.

So let’s dive right in!

In the first part of this series we’ll go through how to:

  1. Install the packages we need.
  2. Import specific components from those packages.
  3. “Wrap the App”
  4. Create the store
  5. Connect a component to the store

Ok, so let’s start first with the packages that we will need to connect our app to Redux. We’ll need ‘redux’ and ‘react-redux’, and they can be installed like so:

Next, we need to import the “Provider” component from ‘react-redux’ in our topmost file; for me, this is index.js

This component establishes the connection between our React app and Redux.

Now that we have our Provider component imported we can “wrap our app”!

Next up: creating our store! This is important because this store will be the “source of truth” for our application: we should also still be in our topmost file where we imported our Provider. It is also important to note that your application should only include one store.
1. Import createStore from ‘redux’
2. Create a variable store where we can save our createStore
const store = createStore()
Note: createStore expects that we will be passing it a reducer. To bypass this for now we can pass it an empty arrow function like so:
const store = createStore( () => {} )
3. Pass our newly created store to our Provider
<Provider store={store} />

Last, but certainly not least for this week is connecting a component to our store! Start by navigating to the first component you wish to connect to the store: I generally start with my App component and work my way out from there depending on where it’s needed.

Within this component, we need to import the connect component from react-redux

import { connect } from ‘react-redux’

Once connect has been imported we now need to wrap our component with connect like so:

And there you have it! We’ve created a store, wrapped our app, and connected a component to the store!

Now keep in mind we haven’t begun to fetch any data, so our store will look pretty empty at the moment, but be on the lookout for the next part of this series where I will be covering creating actions, reducer(s), and mapStateToProps!

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.