React Redux part 1

Today, I wanted to talk a little about React Redux. React Redux is a way to manage state in React. But it also works for other frameworks as well, making it extremely dynamic. With Redux, you get four free functions at your disposal. This will be the dispatch version, part 1 of a series of Redux.

When talking about the dispatch function, it is important to understand that this function is what allows us to trigger state change. What is state? State is data managed by the component and data that is subject to change. Such as a count, or adding a new member, plenty of possibilities of what state can be. In Reactjs, state must be initialized. Usually, in a higher level component, but could be used anywhere. The cool thing about Redux is that with Redux, it doesn’t matter what component you’re in. And for that, we can thank the dispatch function. The dispatch is one of four free functions that comes with Redux. The dispatch function allows us to trigger a state change anywhere! Here is an example of using the dispatch function:

Let’s walk through this. So first thing is that we need to create our store. We can do so by importing createStore from ‘redux’. Then need to create our store variable. Our store variable will be set to createStore and will take in a function. For this example, our function will be “count”. But we’re going to add :

Next we need to make our count function. Our count function takes in two arguments, our set state, and an action. When using our function, it needs to take in some switch/case statements. Very similar to if, else. And it is VERY important to have a default statement. If you don’t add a default statement, it could throw you some errors. Here is what this code looks like:

For this exercise, we’ll call it “incrementAction” but this could be anything you choose. In this case, incrementAction is just an object that takes in key/value pairs. Call it our action. Our action takes in two key/value pairs here. A type and the action we want to do (“INCREMENT”). And we’ll also use a payload here. Our payload will take in an object containing an amount and an account number. The amount is what lets us know how much we want to increment by and the accountNumber is just for fun right now. Once we get a little further, you can see how it all ties together.

Stay tuned for the next part, things are going to get a little more interesting.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store