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.
Are there any advantages of hooks over connect()
regarding software quality?
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.
Personally, I strongly favour using hooks over connect()()
for the following reasons:
connect()()
mapStateToProps
function, whereas you can create multiple hooks for different bits of redux stateconnect()()
effectively causes two React elements to be rendered: the "dumb" element and the connected one. This makes your tree twice as nested!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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With