Is using Redux Hooks instead of connect() good design?
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);
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.