React Blog
Published in

React Blog

Redux in Simple Terms

From this article, I would like to explain to you how to use Redux to solve the same problem which has been solved by pure React differently. Even though this example may not show the actual usage of Redux, you will be capable of getting a proper idea on how to set up Redux for a React frontend.

Suppose you have two React elements. I will name the outer element as OuterElement and the inner element as InnerElement.

Figure 1: Updating state of a outer React component through a callback from a inner React component

To mimic the above scenario I have implemented the following code snippet.

Snippet 1:Updating state of a outer React component through a callback from a inner React component

To represent the outer component’s state I will use an input field called Outer Text. The state value called outerText will be the value for above input field. The function in the OuterElement called onInnerTextChanged is passed as a prop to the InnerElement so that whenever its input field changed that can be notified to OuterElement via that.

Figure 2: Behavior of inner and outer text fields

Lets solve the same problem with Redux

Suppose we use a common store to keep changes happen in all React views and any of them can be observers to that store at any time when they need it.

Figure 3: OuterElement getting the state of InnerElement through a common store.

This is something very similar to what happens in Redux.

Figure 4: How React view can be connected to Redux

As shown in Figure 4, whenever a change which others are interested on happens in the InnerElement it submits that event to Redux store in form of an Action. Action is nothing but a normal object with a type field as a mandate and also other attributes if needed. The action can be dispatched to the store using the dispatcher.

Figure 5: Example action

The State within the store can’t be directly updated (here I will not explain what is the reason for that). The State can only be updated through a layer called Reducer which takes the current state and the incoming action as arguments.

Through out the rest of the article I will show you how the setup in Figure 4 can be implemented step by step.

Create the Reducer and the Store

Figure 6: Create the Reducer and Store

Following code snippet will do the above for you.

Snippet 2: Create the Reducer and Store

Provide Redux to React Views

Figure 7: Provide Redux to React views
Snippet 3: Provide Redux to React views

Connect React Views with the Store

--

--

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