create account

How I found own way to access Redux in React component by vicev1

View this thread on: hive.blogpeakd.comecency.com
· @vicev1 · (edited)
$29.99
How I found own way to access Redux in React component
![](https://miro.medium.com/v2/resize:fit:4800/format:webp/1*qsfrNpkBgDAPT3zKqkLxcQ.jpeg)

Hello, there!

I’ve seen a lot of more articles about React and Redux combination and most of them explaining how to connect these solutions and basic usage. But lets imagine that We have a project a bit larger than the regular todo-list example. Our project have a store with a lot of different modules and hundreds actions.

I would like to show You how I created my own solution without any built-in solutions or packages.

## Trivial solutions
### Props way
The most trivial and easy solution is a providing a store state and actions via props. I won’t describe a full example here You know how it works.
```
connect(mapStateToProps, (dispatch: Dispatch<AnyAction>) =>
  bindActionCreators({<actions_object>}, dispatch))(MyComponent)
```

<b>Pros:</b> Easy to use, fast solution, reactive as well.
<b>Cons:</b> Need to provide each store state item or action manually to a child component(Of course, You may connect each component to the store but there will be a very high-weight components).

### Built-in hooks way
Latest versions of Redux offers us several hooks for accessing to store like:
1. <code>useStore</code> — get the store instance directly;
2. <code>useDispatch</code> — get a dispatch function;
3. <code>useSelector</code> — build a reactive getter from store;
<b>Pros:</b> Easy to use, fast, partial reactive;
<b>Cons:</b> useStore isn’t reactive at all – You may get a state but it will be the snapshot only – not applicable. useSelector isn’t convenient to get a lot of data. You may try to select the whole state and destruct gotten object but it will return the new value each time when main state will be changed. It may cause unexpected behavior.

## My solution
Let’s start with a defining of what we need. I would like to make a hook which will allow getting any state module, property as reactive and getting any action. It should support TypeScript as well, obviously.

Actually, we have to remember about performance and convenience. So, let’s see how it should be used:
```
const { someState, someAction } = ourHook() // someState and someAction provide types automatically
```

Let’s start with creating of custom hook.
```
const useMappedStore = () => {
  return {...state, ...actions}; // Typed
}
```

Firstly, I have to map the store actions, make them dispatchable and return to component. It could be achieved with the built-in redux function <code>bindActionCreators(actionsObj, dispatch)</code>.

Secondly, need to get store state reactively. We may achieve it with hooks above. But how we can get a state dynamically and reactively?
Let’s use a one interest instrument named as Proxy.

```
export const useMappedStore = () => {
  const store = useStore<AppState>();
  const dispatch = useDispatch();

  const storeStateAccessor: AppState = store.getState();
  const storeStateAccessorProxy = new Proxy<AppState>(storeStateAccessor, {
    get(target, p, receiver) {
      return useSelector((state) => state[p]);
    }
  });

  return {
    ...storeStateAccessorProxy,
    ...bindActionCreators(getActions(), dispatch)
  };
};
```

As you can see I used a proxy to creating a selector hook dynamically. Any store state property will be called when component will be created. Pay attention we are not breaking hooks rules.

<i>If We have to support old browsers We could use Object.defineProperty as well.</i>

### Instead of conclusion
I know NPM has a thousands redux helper packages and I just wanted to show you how developer could implement it manually.
Thanks for reading!

<small>Source article: [Link](https://dkildar.medium.com/how-i-found-own-way-to-access-redux-in-react-component-a3272765367b)</small>
<small>Source code: [GitHub](https://github.com/ecency/ecency-vision/blob/development/src/common/store/use-mapped-store.ts)</small>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 72 others
properties (23)
authorvicev1
permlinkhow-i-found-own-way
categorydevelopment
json_metadata"{"image":[],"tags":["development","react","js"],"description":"I’ve seen a lot of more articles about React and Redux combination and most of them explaining how to connect these solutions and basic usage. ","app":"ecency/3.0.36-vision","format":"markdown+html"}"
created2023-10-30 09:54:00
last_update2023-10-30 10:04:42
depth0
children1
last_payout2023-11-06 09:54:00
cashout_time1969-12-31 23:59:59
total_payout_value15.008 HBD
curator_payout_value14.987 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,876
author_reputation982,640,576,246
root_title"How I found own way to access Redux in React component"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,422,956
net_rshares62,890,145,881,496
author_curate_reward""
vote details (136)
@hivebuzz ·
Congratulations @vicev1! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@vicev1/upvoted.png?202310301058"></td><td>You received more than 50 upvotes.<br>Your next target is to reach 100 upvotes.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@vicev1) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/pud-202311"><img src="https://images.hive.blog/64x128/https://i.imgur.com/805FIIt.jpg"></a></td><td><a href="/hive-122221/@hivebuzz/pud-202311">Hive Power Up Day - November 1st 2023</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-vicev1-20231030t110256
categorydevelopment
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2023-10-30 11:02:57
last_update2023-10-30 11:02:57
depth1
children0
last_payout2023-11-06 11:02:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length900
author_reputation370,748,922,733,045
root_title"How I found own way to access Redux in React component"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id128,424,016
net_rshares0