Connect Redux to React app and Cache it in 2.5 minutes

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 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 , , , , 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: , ,

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

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

Added strings: , , ,

Delete attribute to prevent it from changing the page. 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. from 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 by hook. No need to , it’s already included.

Caching on React Native

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

Added strings: ,

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

Thank you!

CDO at Russian TOP-50 IT Supplier for Banks denis@opium.pro