Redux useSelector and useDispatch Hooks
React hooks are an incredibly powerful new addition to React, but their usefulness doesn’t end with the built-in hooks shipped with Reactjs. React allows you to build your own hooks, which allows different libraries that can be used with React, like Redux, to create their own hooks. In this blog post, I’ll break down a couple of the hooks that can be used to optimize your Redux code, specifically useDispatch and useSelector. Normally, to connect a React component to Redux’s state you have to use the connect keyword. Through these Redux hooks, you can eliminate having to use connect completely, simply using the hooks in your component body instead of the export statement.
Above is my container for my employees page in a React application, pre-Redux hooks. To access the Redux store, the Redux documentation tells you to use the mapStateToProps and mapDispatchToProps functions to select the part of the store that the component needs to use and dispatch different actions to the store, respectively. You can see the effects of line 86 in mapStateToProps on line 76, where I use the map method to populate a list of EmployeeCard components with each individual employee found in the store. The mapDispatchToProps function allows me to dispatch the fetchEmployees and fetchTitles requests you see on lines 93 and 94 in my useEffect hook on line 58. If I switched this component to use Redux hooks, I could eliminate the extra functions outside of the component body and get rid of the ‘connect’ call while exporting the component. Getting rid of extra bloat is always a good idea, so let’s see what can be done.
To start, instead of mapStateToProps you can use the useSelector hook. On line 13, I saved an employees variable as the employees portion of the store, which I separated out through useSelector. Below my employees variable, on line 14, I saved the useDispatch hook to a variable, just to increase my code’s readability for anybody reading through it for the first time. I use that useDispatch hook inside the new loadPage function I created to hold the dispatches that were previously inside my useEffect hook. This function uses async/await to run asynchronously and dispatch the fetchEmployees and fetchTitles actions in order to populate the page with information from the store. After implementing these two hooks, this component (and any component using mapStateToProps and mapDispatchToProps) is effective without using connect in the export statement, so after removing that information this component is functional with Redux’s useSelector and useDispatch hooks!