Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using Redux Hooks instead of connect() good design?

Currently there are two concepts how to connect a React component to the redux store: connect() and Redux Hooks. I was wondering whether using hooks is considered good software design.

  • It harms the Single Responsibility Principle because the Component is not only responsible for rendering the data, but also for connecting to the store.
  • There is a tight coupling between the Component and Redux. It will be difficult to reuse the component or to switch from Redux to another state management solution.

Are there any advantages of hooks over connect() regarding software quality?

like image 862
hendra Avatar asked Jan 23 '20 12:01

hendra


2 Answers

Both connect and useSelector/useDispatch are valid ways to interact with the Redux store from your React components. However, they have different tradeoffs. I talked about these tradeoffs in my post Thoughts on React Hooks, Redux, and Separation of Concerns, and my ReactBoston 2019 talk on Hooks, HOCs, and Tradeoffs.

Summarizing: yes, hooks in general lead towards components that do more internally, vs separate components that do different things. Both approaches are valid - it's a question of you specifically want to architect your system.

In terms of "advantages": React-Redux's hooks require writing less total code than connect does, don't add indirection, and are easier to use with TypeScript.

like image 197
markerikson Avatar answered Nov 16 '22 00:11

markerikson


Personally, I strongly favour using hooks over connect()() for the following reasons:

  • Can be easily nested inside other custom hooks to create sophisticated behaviour, which you can't do with connect()()
  • Easier to add/remove from a component during coding and refactoring - the semantics are just less disruptive (you're still exporting the same thing)
  • Separation of concerns - if your component uses multiple different bits of redux state, they all come in through a single mapStateToProps function, whereas you can create multiple hooks for different bits of redux state
  • Simplifies the React tree - connect()() effectively causes two React elements to be rendered: the "dumb" element and the connected one. This makes your tree twice as nested!
  • More intuitive syntax - I find myself often reaching for the docs with connect()(), even though I've used it hundreds of times.

Agree that hooks are a bit more coupled than connect()() - if this is a concern to you, you could add a layer of abstraction:

import { useBadgers } from '../reducers/badgers';

function MyBadgerList() {
    const badgers = useBadgers();
}

with

// ../reducers/badgers.js
export const useBadgers = () => useSelector(state => state.badgers);
like image 32
Duncan Thacker Avatar answered Nov 16 '22 01:11

Duncan Thacker