TzookB

Clean Redux Boilerplate With Hooks

Sun Nov 17 2019

We all love Redux. Well we love the benefits of using a state management system. The huge amount of boilerplate can be a pain in the rear.

But with the "new" react hooks we now have a lot of nifty shortcuts you may consider on using with your new redux/react code.

Let's start with a full blown class component:

class Example extends React {
  render() {
    const { label, onClick } = this.props
    return <button onClick={onClick}>{label}</button>
  }
}

const mapStateToProps = state => {
  return { label: state.label }
}

const mapDispatchToProps = dispatch => {
  return { onClick: dispatch(something) }
}

export default connect(mapStateToProps, mapDispatchToProps)(Example)

As you can see above, we have a lot writing to do, just to connect our store data and methods for this simple component.

Hooks Example

Now let's try the hooks code sample:

import { useSelector, useDispatch } from 'react-redux'

const Example = props => {
  const label = useSelector(store => store.label)
  const dispatch = useDispatch()
  const onClick = dispatch(something)
  return <button onClick={onClick}>{label}</button>
}

So much clutter just got cleaned up here...

And if you still wanna have your code split from redux, you can always have two components like:

import { useSelector, useDispatch } from 'react-redux'

const Example = props => {
  const label = useSelector(store => store.label)
  const dispatch = useDispatch()
  const onClick = dispatch(something)
  return <ExampleView ...{ label, onClick } />
}
const ExampleView = ({ label, onClick }) => {
  return <button onClick={onClick}>{label}</button>
}

P.S. These code examples are not tested, so test them out :)