JAVASCRIPT REDUX

Learn Redux with React – An introduction to Redux

learn-redux-react-encodedbicoding
Written by encodedBicoding

learn-redux-with-react

 

When I first heard about redux and what I need it for, the first thought that came to my mind was why?, but at the same time, I was excited to learn Redux with React.

Note: setting up Redux is overkill for really simple projects – see context-API or component state management.

Because you are here, I would assume you want to learn redux with react, and not bother you with how overkill it is.

Redux is small words, help you manage state throughout your application.

I am sure you are familiar with how component state management works, if not, see How to use component state in react.

React component state helps you ensure that:

  1. Each component maintains it’s own state
  2. If a component needs to share state, it needs to pass it via props.

If you are new to Javascript, start by reading these articles HOW TO BECOME A SOFTWARE ENGINEER

Down-side to this:

  • A component may have to share state down the pole, even to components that do not need to see the data in the state.
  • They could be data change down the pole, which can also cause unexpected behaviour in your application.

How Redux comes in:

Take ‘A’ to be a variable you declared globally, A can be seen and modified by any function in your script. Redux gives us a global state likewise, this state is an object, a reducer does the ‘modification’, only when it receives an action.

Note: Reducers do NOT mutate the state

Now, at this point, actions and reducers may sound strange. Don’t you worry, you will get up to speed soon!.

Since we now have a glimpse of what redux do, let’s find out how it does it.

First, you must have heard (or not) some terminologies about redux, don’t let them scare you, calm down, sit beside a cup of water, and drink when you feel like you don’t understand.

First, we need to have a store, note, this store is just a simple object. This is how Redux comes in, therefore the store is gotten from redux.

I would assume that you already have a react app set up with either webpack or create-react-app

A folder structure you can use is:
folder-structure-encodedbicoding

// store.js

import { createStore } from 'redux'

const store = createStore();

export default store;

But, something is off, the createStore function, won’t work;

  • I explained above how the store-state changes based on actions, and the actions are sent to the store by reducers. The createStore function above needs a reducer passed in as an argument.

Let us create some reducers.

/reducers

    • /exampleReducer
    • /index

// exampleReducer.js

import { SAY_HELLO } from '../actions';

const initialState = { greet: ' '};

////A reducer takes two arguments – An initial state object and an action

const sayHelloReducer = (state = initialState, action) {
switch(action.type){
case SAY_HELLO:
return {
...state,
greet: 'Hello World',
}
default:
return state
}
}

export default sayHelloReducer;

// reducers/index.js

////first, we need to import a package called combineReducers from redux

import { combineReducers } from 'redux';
import sayHelloReducer from './exampleReducer';
const reducers = combineReducers({
sayHelloReducer,
})

export default reducers

combineReducer would return objects containing all the reducers in your project. For now, this project only has one reducer.

Now, Let’s go back to our store.js, and ensure it has the newly created reducer as an argument in the createStore function.

// store.js

//// add the following

import reducers from '../reducers';

//// pass the imported reducers as an argument to createStore function

const store = createStore(reducers);

With this, we now have the reducers ready for actions!.

We have been talking about actions for a while now, but we have not declared or made any.

Let’s make some…

Note: The current state of the store is:

state = {
exampleReducer: {
greet: ' ',
},
}

// action/exampleAction.js

Note: your actions creators are functions that simply return objects. these object are actions. The object MUST have a type property, you can also choose to add other properties if you wish.

const doGreet = () =>{
return ({
type: 'SAY_HELLO '
})
}

export default doGreet

Now that we have our action creators, we can now use them in our components.

// components/greet.js

import React from 'react';
import doGreet from '../action/exampleAction'

const Greet = ({greet, dispatch}) => {
return(
<div>
{greet}
<button type="submit" onClick={dispatch(()=>doGreet())}></button>
</div>
)
}

The above code is almost complete, from the code, we notice the component has a greet and dispatch properties in its props and the button dispatches the doGreet function we declared earlier.

Note that in redux, we dispatch actions, and components can only be able to dispatch actions to the redux store if they are connected to redux. But how do we connect to redux?. react-redux has a connect method, it is a pure function.

With the connect function, react is telling redux to what out for a certain connected component. Lets begin to modify the previous code.

import { connect } from 'react-redux';

now, let’s connect the component.

export default connect()(Greet)

With that code, the component can now dispatch actions, but it doesn’t speak for the greet props that is in the redux state.

This brings us to mapStateToProps. mapStateToProps is just a function declared like so.

const mapStateToProps = state => ({
greet: state.exampleReducer.greet
})

Now let’s modify the connect code:

export default connect(mapStateToProps)(Greet)

with this we are almost done setting up and learning redux.

Now we have redux set up and connected, but… the app doesn’t know how to recognise the state. To remedy this, we need a Provider component from redux, and wrap our entire app in it.

// app.js

import { Provider } from 'redux';

I’m assuming you already have react set up properly. All you need to do now is import store from ./store; then wrap app in Provider.

<Provider store={store}>
<App />
</Provider>

And that’s a wrap on using Redux with React for now. I’ll be teaching on redux-thunk, used in asynchronous functions. stay tuned and share this post.

Have questions? feel free to use the comment section

About the author

encodedBicoding

Software Engineer || Tech Enthusiast.
Ex @andela
Github: https://github.com/encodedBicoding
Geek Name: EncodedBicoding
Real Name: Dominic Isioma Olije

Leave a Comment