Typesafe React Redux hooks
Tags: redux, react, typescript
Published: 2020-07-01 18:56:09

Going from `mapStateToProps` and `mapStateToDispatch` to `useDispatch, useSelector` or custom hooks: What's the benefits? Does typing inference work? 

***

_The code below exists at [github.com/tomfa/redux-hooks](https://github.com/tomfa/redux-hooks/), and I'll be referencing commits as I go along._

## Plan

1. Set up a React Redux with Typescript

2. Implement some redux state, and implement UI using _MapStateToProps_ and _MapDispatchToProps_. (_Referenced to as MapXToProps from now on_).

3. Swap to using built-in Redux hooks.

4. Swap to custom hooks.

## Part I: Set up React Redux with Typescript

### Install React with Redux

```bash
npx create-react-app redux-hooks --template redux
```

And then run it:

```bash
yarn start
```

![React redux starter](https://dev-to-uploads.s3.amazonaws.com/i/x7dk9nlr4hy7220xm4a3.png)

_Nice. The browser should show you something ala the above._

### Add typescript 

Add types and the compiler ([666f61](https://github.com/tomfa/redux-hooks/commit/666f6123f54b938525839cc703deeb1496ffd4b2))

```bash
yarn add -D \ 
  typescript \
  @types/node \
  @types/react \
  @types/react-dom \
  @types/jest \
  @types/react-redux
```

And rename all `.js(x)` to `.ts(x)` files ([54bfd7](https://github.com/tomfa/redux-hooks/commit/54bfd7835589f47cf13aae12f87bf6bb55df6fc4)). You could do this manually (there's only ~10 files), or with the bash snippet here:

```bash
for x in $(find ./src -name \*.js\*); do
  mv $x $(echo "$x" | sed 's/\.js/.ts/')
done
``` 

Ok, sweet. Let's add a `tsconfig.json` with e.g. the following contents ([8b76f82](https://github.com/tomfa/redux-hooks/commit/8b76f82fd98830a99fadd2689164679e464a60eb)):


```json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",  
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}
```

_This config above is from [react-starter --template typescript](https://create-react-app.dev/docs/getting-started#creating-a-typescript-app):_

### General hygenic setup

- Add prettier on commit – [9bd3b32](https://github.com/tomfa/redux-hooks/commit/9bd3b32)
- Run TS check on commit – [c490d79](https://github.com/tomfa/redux-hooks/commit/c490d792eebf72c18d80d0b552fcb692dd844461)
- Add missing types - [0e3a149](https://github.com/tomfa/redux-hooks/commit/0e3a149)

## Part II: Add some state



The app is a simple Chat app, taken from [Recipe: Usage with TypeScript](https://redux.js.org/recipes/usage-with-typescript/). It consists of two UI components:

- ChatInput
- ChatHistory 

Together, they make a dummy chat app that uses Redux. Below is the _ChatHistory_ component:

```tsx
import * as React from "react";
import { connect } from "react-redux";

import { RootState } from "../../store";
import "./ChatHistory.css";

interface OwnProps {}
type DispatchProps = {};
type StateProps = ReturnType<typeof mapStateToProps>;
type Props = OwnProps & DispatchProps & StateProps;

const ChatHistory: React.FC<Props> = ({ messages }) => (
  <div className="chat-history">
    {messages.map((message) => (
      <div className="message-item" key={message.timestamp}>
        <h3>From: {message.user}</h3>
        <p>{message.message}</p>
      </div>
    ))}
  </div>
);

const mapStateToProps = (state: RootState, ownProps: OwnProps) => ({
  messages: state.chat.messages,
});

export default connect<StateProps, DispatchProps, OwnProps, RootState>(
  mapStateToProps
)(ChatHistory);
```

_Diff [e877b50...6efc2a2](https://github.com/tomfa/redux-hooks/compare/e877b50...6efc2a2) shows the whole code for these components._

### Typing inference works great! 

- **Automatic property inference** with these lines of boilerplate (in each connected component):

```tsx
// ../ChatInput.tsx
interface OwnProps {}
type DispatchProps = ReturnType<typeof mapDispatchToProps>;
type StateProps = ReturnType<typeof mapStateToProps>;
type Props = DispatchProps & StateProps & OwnProps;

...

export default connect<
  StateProps,
  DispatchProps, 
  OwnProps, 
  RootState
>(
  mapStateToProps,
  mapDispatchToProps,
)(ChatHistory);
```

- **Automatic store type inference** with this:

```tsx
// ../store/index.ts
export type RootState = ReturnType<typeof rootReducer>;

// ../ChatHistory.tsx
import { RootState } from "../../store";

const mapStateToProps = (state: RootState, ...
```

TypeScript tells me if my store value has the wrong type when added to JSX, and also when passing the wrong input type into action payloads. It works neatly!

One frequently mentioned drawback of Redux is the amount of boilerplate. Typing definitely adds to this with connected components. Let's see how hooks simplifies it.

## Part III: Converting to hooks

### ChatHistory: replace with hooks

```tsx
// import { useSelector } from "react-redux";
// import { RootState as S } from "../../store";

const messages = useSelector((state: S) =>  state.chat.messages);
```

_Diff: [1310a50](https://github.com/tomfa/redux-hooks/commit/1310a50)_

ChatHistory only used State. I feel the readability of the code is better, and it's also  shorter, going **from 29 to 21 lines**. Almost zero boilerplate.

### ChatInput: replace with hooks

_Diff: [988ee06](https://github.com/tomfa/redux-hooks/commit/988ee06)_

ChatInput went from 70 to 57 lines, with a total **codediff of -13 lines** (being the only changed file). I still decided to keep the UI-related logic outside of hooks, so the difference isn't as large as it could be.

Again, I think the diff makes the component read better. Almost all the boilerplate code is gone! Even without most of the typing-related code, the inference is intact.

## Part IV: Replace hooks with custom hooks

_Diff: [1c5d82f](https://github.com/tomfa/redux-hooks/commit/1c5d82f)_

ChatInput goes from 57 to 34 lines, but since we're adding two new _hooks_ files, we end up with a **+14 code line change** compared with built-in hooks. 

With custom hooks, we can rename things as we please, and all we end up with (relating to redux) is: 

```tsx
const { inputValue, setInputValue, submit } = useChatInput();
const { userName } = useAuth();
```

It does require us to add (and maintain) extra "hooks files", but I think it reads _very easily_. 

The separation of concerns is clear, with clean ability to reuse logic across components. Though this commit is some extra lines of code, it could become fewer if the hooks are reused; even just once.

### Summary

The overall change from MapXToProps to using **built-in hooks** can be seen in the diff [c22c184...988ee06](https://github.com/tomfa/redux-hooks/compare/c22c184...988ee06)

The change from MapToProps to using **custom hooks** can be seen in the diff [1310a50...1c5d82f](https://github.com/tomfa/redux-hooks/compare/1310a50...1c5d82f)

- Type checking was preserved throughout the changes.

- Code size decreased when changing to built-in hooks. 

- Code size was equal when changing to custom hooks (before any reuse).

- Component with hooks [will rerender when parent rerenders, unlike with MapXToProps](https://react-redux.js.org/api/hooks#performance). However, this can easily be fixed with `React.useMemo` wrapping the component.

Overall, I do not see good reasons to keep using MapXToProps. Hooks seem more consise and readable.

Tell me if I've missed something :)

***

_Feature image is by <a href="https://unsplash.com/@polarmermaid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anne Nygård</a>_