A neat way to add Redux computed value by custom hook

DylanJu
2 min readOct 6, 2020

--

Someone who starts react project usually have to decide a global state library redux or mobx.
redux has more stars in github than mobx but mobx has a unique point with @computed. It is an easy way to get computed value with javascript decorator pattern. Of course, `redux` can do the same thing by using reselect library.

As react implement ‘hook’, developers can make easily the computed value.

Assume you have fruitStore keeping price and discount data fetched by your server.

This data will be displayed in 3 ways at Tag Component.
1. discounted price
2. final billing price to the payment
3. readable discount value with ‘%’

for this, you have to calculate as below

If have multiple components using these values, you have ctrl + c, ctrl + v. It makes it harder to read and re-write code.
You may think the store keeps these all data in redux. But it may force the nested object structure and become more complex as view component incremented.

Then let’s write simple and efficient code with useMemo and custom hook.

This way makes computed value without another library reselect or mobx. By using useMemo, you can use cached value and maintain easily code even if view and fruits incremented. And also, the most important thing I think is that you can distinguish various logic as you want.

p.s
This article means not that useMemo can replace reselect or what. You can read more details from [here](https://github.com/reduxjs/reselect/issues/386)

--

--

DylanJu
DylanJu

Written by DylanJu

당근페이 Frontend-developer

No responses yet