Convert Redux to Hooks

Convert Redux to Hooks

In this article, I will try to explain how you can use Redux with React Hooks.

React Redux gave support for Hooks in version 7.1 which was released on 11th June, 2019. It means that you can use Redux with Hooks in your functional component instead of using connect higher order component (HOC).

What are Hooks?

Just to refresh a little about hooks, hooks were introduced in React version 16.8 and it allows you to access state and life cycle methods in functional components.

Let’s have a look at an example.

React class component like this:

class Count extends React.Component {
  state = {
    count: 0
  };
  add = () => {
    this.setState({ count: this.state.count + 1 });
  }
  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick?={this.add}>Add</button>
      </div>
    );
  }
}

Can be written as a function component using Hooks like this:

const Count = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick?={() => setCount(count + 1)}>Add</button>
    </div>
  );
};

If you want to explore more about hooks, I would suggest you to go through the detailed docs on hooks.

Back to Business:

Original purpose of this article is to explain how we can use Redux with Hooks.

React Redux now offers useSelector and useDispatch hooks that can be used instead of connect.

useSelector is alternative to connect’s mapStateToProps. You pass it a function that takes the Redux store state and returns the state which you need.

useDispatch replaces connect’s mapDispatchToProps. All it does is return your store’s dispatch method so you can manually dispatch actions.

Enough theory? Alright let’s have a look at real-time example in which we will convert a React component that used connect into one that uses Hooks.

Using connect:

import React from "react";
import { connect } from "react-redux";
import { addCount } from "./store/counter/actions";
export const Count = ({ count, addCount }) => {
  return (
    <>
      <div>Count: {count}</div>
      <button onClick?={addCount}>Count</button>
    </>
  );
};
const mapStateToProps = state => ({
  count: state.counter.count
});
const mapDispatchToProps = { addCount };
export default connect(mapStateToProps, mapDispatchToProps)(Count);

Now, with the new React Redux Hooks instead of connect:

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addCount } from "./store/counter/actions";
export const Count = () => {
  const count = useSelector(state => state.counter.count);
  const dispatch = useDispatch();
  return (
    <>
      <div>Count: {count}</div>
      <button onClick?={() => dispatch(addCount())}>
        Count
      </button>
    </>
  );
};

As you can see, code is precise, fewer in lines means better performance, easier to read, easier to understand and of-course easier to test.

Another benefit of not using the higher-order component is that you no longer get this “Virtual DOM chaining”:

Now you have basics of Hooks and how to use them with Redux, time to get your hands dirty with the detailed documentation.

You learnt something new today? Comments and feedback always make the writer happy ;)

About the Author:

Having 7+ years of professional software development experience in various cutting edge technologies, currently working as a Principal Software Engineer in a silicon valley based company in full stack capacity using ReactJs and Apollo-GraphQL. I love to write about technology and share my professional experience with everyone.


Muhammad Ghazanfar Ali

Lead Frontend Engineer | React | React Native | JavaScript | UI/UX Specialist | Actively Seeking Frontend Tech Roles globally

5 年

Muhammad Anser?I'm really thankful to take this topic and writing for people who do not have this in their knowledge. I really liked the way of writing. Concept was delivered so easily. Thanks a lot.

Adnan Shuja

Senior Software Engineer at Abu Dhabi Digital Authority

5 年

Nice article but having an arrow function inside the render can cause performance issues as it will create a new reference to the function everytime component gets rendered. Your thoughts??

要查看或添加评论,请登录

Muhammad Anser的更多文章

  • How to make an offline first React App

    How to make an offline first React App

    I did a POC on offline first React app and decided to share my POC with the developer community. Suppose we are to…

    7 条评论
  • Convert traditional GraphQL Query to?Hooks

    Convert traditional GraphQL Query to?Hooks

    If you don’t know about React hooks and how to use them with the GraphQL API, have a look at this article first…

  • Why I turned down job offers from some big companies

    Why I turned down job offers from some big companies

    When there are more job seekers looking for work than jobs available (think: the Great Recession) it’s rare for…

    2 条评论
  • Using React Hooks with the GraphQL API

    Using React Hooks with the GraphQL API

    What are Hooks actually? Hooks are the functions that lets you get to 'state' without using a class component. Rather…

    1 条评论
  • ReactJS or AngularJS, which to choose

    ReactJS or AngularJS, which to choose

    In the previous couple of years, sites have developed into complex web applications, and what used to be place that is…

  • 5 quick JavaScript hacks

    5 quick JavaScript hacks

    1. Bool condition check This is one of the basic oversights that each software engineer would have done at least once…

  • Things I learned so far as a Software Engineer

    Things I learned so far as a Software Engineer

    I'd love to share five of the most imperative things I've adapted up to this point; I believe that all developers…

  • You can’t hide from Facebook

    You can’t hide from Facebook

    Facebook has since quite a while ago enabled you to download a chronicle of the considerable number of information the…

  • Front-end vs Back-end. Which and Why?

    Front-end vs Back-end. Which and Why?

    I have been working as a developer for more than 5 years now, having almost 3 years experience in backend development…

  • Being toxic in workplace

    Being toxic in workplace

    I have been working as a software engineer for more than 5 years now. I have worked in typical software industry as…

    4 条评论

社区洞察

其他会员也浏览了