Introduction to React Hooks, Simplify your Components [New Feature 🔥]

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

What is React Hooks?

React Hooks are a new Feature will be added in the next release as soon the RFC Approval, right now it is on alpha version and still in development so it's not wise to use it on your production project or with other dependencies since most of them don't support it by the time of writing this tutorial.

If Hooks are already supported on a stabled version then you still can follow along with the tutorial and pretty much understand it's main usage functionality.

This tutorial assumes you know the basics of React and worked with it before so you could easily follow along without issues, however, if you are new to React and want to learn you can start from Here.

You can grab the Repository of React Examples and hooks from Github.

First, since the hooks feature still in development and it's currently in alpha phase so we have to install this specific version in order to experiment with and use the Hooks.

npm install react@16.7.0-alpha.2 react-dom@16.7.0-alpha.0 --save-dev 

Once the alpha versions of React and ReactDom are installed, NPM is going to throw warning says that dependencies that you are installing on your project have conflict which basically means that those third-party libraries still haven't added the support for the new versions yet, so you need to avoid using the alpha versions with any of those libs.

Let's go back to our main question (What is a React Hooks) basically, hooks are a one function API that allows you to create and use class component state without even writing a class, at first it may seem kind of unnecessary at first but you still need to look at a real world example to understand how much it can help you simplify your components without losing its feature and function.

Why use Hooks?

Actually, this is a good question to start off with.

So, imagine this scenario: you have a simple class Counter component that renders a div holds the current count number and a button to increment the number on click, and it does that all on it's own so all we have to do is just render it on the main App component as a child, here is how it looks like:

//Counter, increase num onClick
class Counter extends React.Component {
  constructor() {
    super();
    //Initial State Value(s).
    this.state = { counter: 0 };
  }

  incrementCounter() {
    this.setState(prevState => ({ counter: prevState.counter + 1 }));
  }

  render() {
    //Extract counter 
    const { counter } = this.state;

    return (
      <div>
        <div>Counter: {counter}</div>
        <button onClick={this.incrementCounter.bind(this)}>
          Increment Counter
        </button>
      </div>
    );
  }
}

And simply render it in the main App component.

//We need to export The App in order to render it to the DOM using ReactDOM
export default class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <CounterHook />
      </div>
    );
  }
}

If you try now to build the react source files either using react-create-app or your own Webpack build configuration you will notice a div with a button that does increment the value of the counter by one on each click.

Now let's try to create pretty much the same Counter component above but this time we won't need a class we just use a function component that returns a React JSX to be rendered as a normal component.

Usually, function Components don't have a state in fact if we needed to have a state on a component then we have to use a Class and here where the main benefit of using Hooks.

Some of you how has worked with React for a quite some time now that it is not really great to create a class for a simple component as the Counter since it's very straightforward and all it does is increment the state on a button click, so we can use new React's Hooks.

import React, { useState } from "react";
//Function Component (works as a custom hook)
function CounterHook() {
  //useState Hook returns an array with current value and function to setValue 
  //useState has it's inner state manager so it works as a component but it simplify things for us 
  const [counter, setCounter] = useState(0);
  
  return (
    <div>
      <div>Counter: {counter}</div>
      <button onClick={() => setCounter(counter + 1)}>Increment Counter</button>
    </div>
  );
}

We first need to import React builtin hooks (standard) from the main React module.

Then on the Functional Component, we use the useState hook (notice: that by naming convention hooks start with use).

When calling the useState we pass it the initial value and since the counter is a number so we pass 0 as a start value, the hook function returns an array so we use the array extract syntax (ES6) in order to get the value and it's function to set the value you can take it as the state object property and the setState to set value of the counter but instead of creating a class and a state object for it this hook function does everything on its own by containing your state and all the needed features to update the state and allow for state update and component re-render.

  • (counter) is the current value (it takes the initial value 0 at the first render).
  • (setCounter) takes the new counter value as an argument and updates it on its own inner state so you don't have to worry about managing that, it all happens behind the scenes, (works the same as setState on a class component).

And finally, return your JSX element to render since it works the same as a class (render) method but this time in a much minimal and easier way to read and understand.

Now, you can try to replace the Counter class by CounterHook on the main App component and you should see no difference since they pretty much work the same way.

When to Use Hooks?

Well, the best scenario to use hooks on your components instead of using a class component is when the class component you trying to make is either so minimal to hold and manage its own state like the Counter class we have above since it all does is having one variable on the state object and tries to create a whole class for it is a bit off.

  • Create simple and fast working components 
  • Adding state for function components
  • You need a very minimal and a small component 

Notice: there is more than one built-in hook that you can use, but everyone has its own functionality and constraints.

When you create a functional component and you use in it a built-in Hook this way you are creating your custom hook too since hooks manage state in a much simpler way.

When to Not Use Hooks

As using hooks is an awesome way to do things faster and easier on a much bigger scale, but still, it has its own constraints when you mustn't use hooks in under any circumstances.

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — your own custom Hooks. We’ll learn about them in a moment).

Hooks Lifecycle

As if you would use Class Component lifecycle methods (componentDidMount or ComponentDidUpdate) for hooks you can use it as the same way you did with the state but this time using the effect hooks which basically a hook that takes a callback that gets executed on (ComponentDidMount and ComponentDidUpdate).

function CounterHook() {
  const [counter, setCounter] = useState(0);
  //the same as using ComponentDidMount or ComponentDidUpdate
  useEffect(() => {
    //Update the Document (page) Title
    document.title = `You Clicked Me ${counter} times`; ///< using String Literals
  });

  return (
    <div>
      <div>Counter: {counter}</div>
      <button onClick={() => setCounter(counter + 1)}>Increment Counter</button>
    </div>
  );
}

As you can clearly see you can do the same thing of useState but this time using the useEffect hook that takes a callback which gets called (executed) once the componentDidMount or ComponentDidUpdate component lifecycle have been invoked so you still have your class component lifecycle methods that you love ready-made to be used from hooks.

For handling, componentWillUnmount, you can return a callback (function) at the end of the useEffect hook callback that will get invoked on the Component Unmount (by the component we mean the functional component that the hook lives in).

What's Next

Now You have got a quick overview of what hooks are and why you should consider using them on your next application also, make sure to check the Official React Docs for more detailed info on other hooks that we haven't covered on this tutorial and their use cases and constraints.

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games