DEV Community

Aymen Marouani
Aymen Marouani

Posted on • Updated on

React Hooks to Tame the Complexity

Hooks are a new feature introduced by React 16.7.0-alpha that allows the use of state (and other features like context, store or life cycle) outside the scope of a class namely in a pure function. React hooks were first introduced (alongside other features like Suspense, Time Slicing and Profiler) to the public in ReactConf 2018 by Sophie Alpert and Dan Abramov (one of the creators of Redux).

Motivation and Background

React Hooks are meant to solve some problems and limitations that the React Team in Facebook noticed. We can summarize those limitations in three main problems:

  1. "Wrapper Hell": components as classes tend to clutter in a big intricate hierarchy that has to pass properties between them and encapsulate each other. This can be seen in big projects where extra layers of abstraction wrappers serve to pass properties and extract reusable logic. Things become more complicated when forced to update the structure of the hierarchy by moving component with their wrappers.
  2. "Giant Component": when creating a component, we need usually to implement its life cycle methods (componentDidMount, compnentWillUnmount ...) and it's hard to separate them from the class, so this will increase component's size when we have to add more logic to them.
  3. "Hard Classes": a stateless react component written as a function requires more effort to migrate it to a class form. In addition, the React Team noticed that classes are hard to optimize by the compiler.

The above limitations have as source the fact that React doesn't have a smaller unit than the class context to encapsulate statefull behavior. In their way to solve this problem, the React Team opted for the first time to adopt the RFC approach (Request for Comment) and started tackling the root cause (the atomicity of the class) by restraining the solution to the following main criteria:

  1. "opt-in": the solution must be neither mandatory nor intrusive, i.e. it'll not oblige the current code to adopt them and it can be removed without collateral effect.
  2. "retro-compatible": don't break the current code. Hooks can live alongside class components.

Introducing React Hooks

Simply a Hook is a function that fetches React context data for the functional component. In order to enable this feature, we have to import a React version above 16.7.

Let's consider this simple introductory example:

import React, { useState } from 'react'
import ReactDOM from 'react-dom'

function SimpleHook() {
  const [count, setCount] = useState(0);

  return (
    <React.Fragment>
      <div>A Simple Hook</div>
      <div>the count is <span>{count}</span></div>
      <div>
        <button onClick={() => setCount(count + 1)}>Increment</button>
        <button onClick={() => setCount(count - 1)}>Decrement</button>
        <button onClick={() => setCount(0)}>Reset</button>
      </div>
    </React.Fragment>
  );
}

const mountPoint = document.getElementById("app");

ReactDOM.render(<SimpleHook />, mountPoint);
Enter fullscreen mode Exit fullscreen mode

this example creates an increment decrement control on a given integer displayed as a label.

Simple Hook

In this example we have a page that uses a single functional component. With Hooks, it has a state accessed by importing the useState function and initialized using the directive

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

We declared both the state and the set-state by calling useState and passing the initial value 0. Changing the state is done by calling the previously declared state setter

<button onClick={() => setCount(count + 1)}>Increment</button>
Enter fullscreen mode Exit fullscreen mode

useState is the simplest Hook and we have various types, mainly:

  • useEffect, provided for life cycle behavior implementation (same purpose as componentDidMount, componentWillUnmount)
  • useContext, to access React context API (sort of a global state container)
  • userReducer, to manage local state using pure functions called reducers

More details on how to use those Hook types in this URL. Custom Hooks can be also defined as shown in this section from React Hook API reference.

Conclusion

Hooks are the new way for React to define elementary function based components by allowing a statefull behavior outside the old class definition. They'll live with the legacy and promote design flexibility and code reuse.

References

For more details you can consult the following links:

Top comments (0)