DEV Community

ThankGod Ukachukwu
ThankGod Ukachukwu

Posted on • Edited on

Designing Google Calculator with React Redux Hooks

Preamble

Redux made complete sense after I watched the video tutorial by Dan Abramov — the creator of Redux — and the tutorial by Reinald Reynoso. See the reference list at the end of the article.
Though I am late to the Redux party but I still think it is worthwhile writing this tutorial. Especially for those coming newly to React Redux that would find any relevant knowledge useful. This one could pop up in their frenzy search for knowledge.

The Concept

Redux “is a predictable state management library for frontend frameworks”. It’s popular in React. There are others like Mobx, Flux. But Redux’s simplicity and thinness makes it a library of choice in React.

One thing they often say about Redux is - “finding the right use case”. So somehow you need to have an application where you need to save state.
Don’t think you’d need some kind of complex application to use Redux. The simplest application where you need to save some state can suffice. I was thinking I have to get involved in a big project where I need to save user details, like school management or hospital management application or a social media app or an enterprise application before I would find that ‘use case” . Turned out that the calculator I designed to deepen my knowledge of React needed Redux because it could use some state saving.

I attempted to design the calculator you find when you type “calculator” or “Google calculator” on Google. The picture below is the one I developed, click here to see it.

Simple Calulator

How it Works

That calculator has “Ans” button to retrieve current answer, it saves the answer in memory, and also shows you the operands above the upper display. You can recall the last answer with Ans and use. When you do a computation, you replace the answer with the result or mathematical expression. If you press AC (all clear), you clear everything including the Answer saved. On start, Once you click a number (operand) or operator, the answer updates to 0 . If you do a calculation, the upper display shows you the expression, and display the answer in the lower display.

War Games

So here’s where Redux comes in. On start, as soon as we click a clickable operand/operator, the answer updates to 0. When we finish a calculation and click equal, we update answer and display the expression. If we click on Ans button. We will retrieve the answer and use in an expression. If we click a new operand or operator, we start a new computation but our previous answer is still saved. So tracking this state I think can be done with Redux, I don’t think it may be the most appropriate use case but that’s what I did. So we have three states - EQUAL, OPERATION and CLEAR.

To use redux we have to install it. You should have created your app with npm create-react-app MY-APP and before then installed CRA (create-react-app) all with npm or yarn. And get the React binding.

npm install redux ………………………………………………………………
npm install react-redux ………………………………………………………

Our actions and reducers are the main building blocks of using Redux. These are functions. Normal functions. Only that it’s recommended to use pure functions. A pure function returns a predictable result and do not have observable side effects. A pure function should not have side effects that causes our state to be unpredictable, such as accessing databases, running computations that do not bring the same outcome all the time. However, Redux Thunk solves the problem of asynchronous behaviour. See reading list at end for more. Also see the third video in Dan Abramov’s egghead video tutorial.

Pure/Impure Functions

Take Action And Reduce The Tension

So your actions are functions that ship plain objects to Redux store to be accessed to manage state. One of the object member should be a enumerable type. Such as STORE, OPERATION, CLEAR. Here are the action objects used in the Calculator. Each action describes if we are doing an operation, get the result of expression using equals operand or clearing the display.

Actions

Reducers are functions which are fed into the Redux store which uses a switch statement based on the action sent returns a desired state or the default state. Here's the reducer for this Calculator. Our actions are imported into the reducer. We insert the initialstate (depending on the logic of our application) and create the store. The createstore method can be fed the initialState too. It takes a third argument which can be a middleware like Redux Thunk. We can combine reducers and pass them into the createstore method if you have multiple reducers to track.

Alt Text

Then we go to the component which needs redux and feed in the provider of the store to our component. For this use case, it’s the App.js where the calculator component lives.
Alt Text

Now to the Calculator components. Find screenshots of relevant parts below. It uses functional components and hooks.

Calculator

We need the useDispatch and useSelector hooks for functional components. The useDispatch is to to send actions which delivers state objects to our store. The selector is used to access the state of the store. Here is where I used them below. I used this function to add the operand and operators and I need to track the state.

Dispatch
When computation is done. Answer to expression computed is dispatched. When AC, cleans up the display area too.

Dispatch

So basically we are able manage the three state we need. Something tells me this can be done with ordinary hooks. In the bid to learn I have to make up a use case.

Find below where I assessed the value from useSelector.
HTML

useSelector returns the state object. So don’t mistake it and put a [] around it. Like other hooks that return an array. Access it like a normal object. About preloaded state. On the Redux documentation, they discussed preloadedState in which the createStore method should be given a preloadedState to set initial state. Else it will be undefined. createStore takes three parameters, the reducer, preloadedState, and enhancer. PreloadedState State should be a plain object. Don’t pass in for instance “initialState” instead of initialState() which is one of your actions that returns a plain object. Then if you didn’t give it a preloadedState, the useSelector returns a DefaultRootState which is undefined.

Redux may not be the silver bullet in state management even in React. Kent C Odds has done a good tutorial on using Context API. You can read the list at the end and also one written by Ebenezer Don who said we should discard React + Redux and use hooks + Context.

Nonetheless. This is what Redux does, manages application state. This is just basic. Watch Dan Abrov videos for more.

From the Experts:
Dan Abramov’s videos, see video 3 for pure functions and the rest of it for basic and advanced Redux.!
Reinald Reynoso’s tutorial, one of the two that made it make sense.
Tania Rascia is comprehensive guide, it includes middleware usage Redux thunk for asynchronous behavior.
Kent C Odds (another React guru) advised that we “use context only when prop drilling really becomes a problem”.!
Ebenezer Don thinks we should all “Use Hooks + Context, not React + Redux”
For replacing Redux with custom hooks, see Jolanta’s tutorial.
Meanwhile the calculator is a work in progress.

Staysafe

Top comments (0)