top of page
Search
  • Writer's pictureSeiji Ralph Villafranca

Cleaning your React code with Redux Hooks

Updated: Aug 8, 2021

Redux is very useful in managing data in React especially in large/enterprise scale applications, It gives us the power to store all the moving in our application in one container to maintain a consistent flow and state of values.


Redux is a very powerful library for React but it also possesses downsides especially in the process of developing our applications. One major thumbs down is when we connect our store in our components, this can produce boilerplate codes and from my point of view, it is very tiring to write the code!


Using Connect from react-redux


In the example below, we will use the typical connect function from react-redux library to allow our component to communicate with our state, we will create a mapStateToProps() and mapDispatchToProps() function that will map the state and the actions in the components props respectively.


const mapStateToProps = (state, ownProps) => {  
    return {  
       blogs: state.blogs.allBlogs  
       } 
}  

const mapDispatchToProps = (dispatch, ownProps) => {  
return { 
    actions: bindActionCreators(Object.assign({}, blogActions), 
             dispatch),  
     toastr: bindActionCreators(Object.assign({}, toastrActions), 
            dispatch)     
    } 
 }  
export default connect(mapStateToProps, mapDispatchToProps)(Index);

we assume that we have successfully configured and wrapped our application successfully with Redux and we are now ready to connect our component with the store, the first thing we need to do is to map the states and actions in our components, this can be achieved by creating two functions mapStateToProps() and mapDispatchToProps() and we will pass the two functions as parameters in the connect.


After connecting our component with the states and actions, we can now access the props of the component to dispatch actions get state values.


import Layout from "../components/Layout";
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as blogActions from '../store/blog/actions';
import BlogItem from '../components/BlogItem';

const button = {
 marginRight: "0px",
}
class Index extends React.Component {
 constructor(props, context) {
 super(props, context);
  }
 render() {
 const { blogs } = this.props;

 return (
     <Layout>
        <div>
          {blogs.map(blog =>{
             return (
                <BlogItem key={blog.id} blog={blog}></BlogItem>
                          )
                      })}
          </div>
      </Layout>
 
        )
    }
    
   componentDidMount() {
     this.props.actions.getAllBlogs();
   }
    
}
const mapStateToProps = (state, ownProps) => {
 return {
 blogs: state.blogs.allBlogs
    }
}

const mapDispatchToProps = (dispatch, ownProps) => {
 return {
 actions: bindActionCreators(Object.assign({}, blogActions), dispatch),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Index);

Noticed something in the example? the component here is just trying to display the list of available blogs and there is too much code baked already and this does not stop there, in the future, we may need to access more states and dispatch more actions so we need to bind more in our props causing our mapStateToProps() and mapDispatchToProps() to grow.


With this method, we can ask that is there a way we can just access the states and actions directly by not binding them in the components property, well the answer is yes!

and this is where Redux hooks saves the day.


Using Redux Hooks


Hooks simplifies the process of connecting our states with our components, lets compare how hooks work with the previous method. In the previous example we are using mapStateToProps() to get the values of our state, this will now be done by the useSelector hook and the mapDispatchToprops() which binds our available actions to allow us to dispatch actions will now be done by the useDispatch hook. Let's take a look on the example below.


useDispatch() hook

 const dispatch = useDispatch();
 dispatch(blogActions.getAllBlogs())

useSelector() hook

const blogs = useSelector(state => state.blogs.allBlogs);

import React, {useEffect} from 'react';
import Layout from '../components/Layout'
import * as blogActions from '../redux/actions/blogActions';
import { useDispatch, useSelector} from 'react-redux';

const Index = () => {
    const dispatch = useDispatch();
    useEffect(() => {
           dispatch(blogActions.getAllBlogs())
        }, [])
     const blogs = useSelector(state => state.blogs.allBlogs);
    return (
        <Layout>
          {blogs.map(blog => {
             return (
                 <div>
                   {blog.title} <br></br>
                   {blog.description}
                 </div>
                    )
                })

           }
         </Layout>
        )

}
export default Index;

we can see that we didn't have to connect our component in our store, the hooks can access the actions and the state values in our store directly which eliminates boiler plate codes, I have also used the useEffect hook to call the dispatch action only when value of the blog changes.


And that's it we have simplified our redux code using Hooks, to learn more about React Redux, go to my tutorial: https://www.seijivillafranca.com/post/creating-a-crud-react-app-with-next-js-and-redux I've also used Next.JS to create this tutorial.


Hope you learned and enjoy this short tutorial.

79 views0 comments

Recent Posts

See All
bottom of page