Connect Redux to React app and Cache it in 2.5 minutes

Denis Elianovsky
2 min readAug 8, 2021

Motivation

Redux is awesome. It really helps to handle all the data in our apps.

But it’s hard. Not so hard, but it definitely confuses new developers, coming to you project. Junior developers forget to add reducers, do dispatch stuff, to connect components to the store etc. At some point it leads to a mess.

We make a lot of Fin-tech projects with React+Redux (also on React Native) and decided to simplify Redux usage, so any new developer could easily start working.

And the best solution is to use the common standard. Not the new one, but the one which is already widely used — Hooks.

For the beginning

I presume that you already have your app repository. The one, created by create-react-app is great. I will show the example using it.

So, for testing you can to use it as well

npx create-react-app my-app
cd my-app

Start counting, it takes 2.5 minutes

#1. Install `master-hook` package

npm i master-hook

Don’t worry about redux , react-redux , redux-thunk , reselect , they are already included.

#2. Create ‘src/hooks.js’ file

  • Name your storage
  • Set initial state
  • Set how long the value has to stay cached in ms

#3. Add Provider to `src/index.js`

Added strings: 5 , 9 , 11

No need to pass storage or combine reducers, they all are already in MasterHook.Provider

#4. Use your hook in `src/App.js`

Added strings: 3 , 6 , 13 , 16

Delete href attribute to prevent it from changing the page. setMyName action is created automatically.

No need to connect to the store. It’s already connected.

That’s all!

npm start

You are connected to Redux. myName from myStorage is cached for 10 seconds. You can click the link, reload the page and make sure it is.

Advanced usage

Actions

Of cause you can add actions and selectors. Here is an example with creating an action:

You can obtain values and setters right in your actions.js by useStorage hook. No need to dispatch , it’s already included.

Caching on React Native

It also works on React Native. You just need to specify the native localStorage

Added strings: 8 , 10

You can find the description of full functionality by the link https://github.com/opium-pro/master-hook

Thank you!

--

--