Here is why I love React Hooks

The latest ReactJS release contains a lot of new APIs but also some deprecations. Here is the video from the React Conf 2018 where you can learn more about the new changes.

This library is more powerful than ever. One of the features I really like is the React Hooks.

According to the official documentation:
“Hooks are a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha and being discussed in an open RFC.”

Here is a sample code using that:

  
  
import { useState} from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>You clicked {count} times</button>;
}
  

This new function useState in the code above is a Hook and takes only one argument which is the initial state. Here is how the same thing is achieved without using Hooks.

  
  
import React, { Component } from 'react'

export default class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
    this.setCount = this.setCount.bind(this);
  }
  setCount(value) {
    this.setState({
      counter: value
    });
  }
  render() {
    return <button onClick={() => this.setCount(this.state.counter + 1)}>You clicked {this.state.counter} times</button>;
  }
}
  

React Hooks makes components more reusable.
Until now, we could share code between React components using a prop whose value is a function or by using higher-order components. Using these patterns makes code harder to debug and maintain. With Hooks, stateful logic can be extracted from the component and reuse it without changing the component hierarchy. Apart from being more reusable, it also makes testing components independently much easier.

There will be less spaghetti code.
Because React is so flexible, is very easy to use come up with a bad pattern. As the application grows, components also grow and their stateful logic becomes a mess. Most of the times the lifecycle methods will contain a mix of unrelated logic which will cause bugs and inconsistencies. The great thing about Hooks is that it will let you split one component into smaller functions and using lifecycle method in every component will be a thing of the past.

One example of where Hooks can help is having a component that performs some data fetching by calling an API inside componentDidMount and componentDidUpdate. Most likely componentDidUpdate will contain other unrelated code which can cause bugs. Apart from that you might also have to clean the event listeners inside componentWillUnmount. As you can see, all this related code is split in 3 lifecycle methods.

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment