DEV Community

Cover image for React Hooks (from Class to Functional)
Ryan Kuruppu
Ryan Kuruppu

Posted on • Updated on

React Hooks (from Class to Functional)

This tutorial will guide you through what React Hooks are and the main changes you'll need in order to shift your React components over from Class Based Components to Hook Based Components.

The tutorial is broken down into separate pages to make sure that everything isn't clunked up together

🔖 Table of Contents

  1. Pre-Requisites
  2. What are Hooks
  3. useState Hook
  4. useEffect Hook
  5. useMemo Hook (To be made)
  6. useCallback Hook (To be made)

Pre-Requisites?

Just make sure your React Version is 16.8 or higher.

If you have react globally installed just check the version by using,

npm ls react-native -g
Enter fullscreen mode Exit fullscreen mode

Or check your package.json if you already have a existing project.

What are Hooks ?

React hooks are new way of using state and other react features without the need for classes. They stem from the old React way of writing stateless components using normal functions and add features on top of it so that you don't need to write JavaScript(or TypeScript) classes anymore for the features (like stateful components) given to us in React.

What hooks are we going to look at

There are 10 hooks given to us by React. But we'll be discussing the more commonly used hooks as well as how to use props in React functional components just in case you're new to using functional components as a whole.

  1. useState
  2. useEffect
  3. useMemo
  4. useCallback

You can check out the other hooks provided by React from the docs

Functional Components

Let's take a quick look at functional components before we head into the hooks.

Functional Components in React were initially only used to describe stateless components. Even with the introduction of hooks they can still be used as stateless components by simply leaving out the useState hook from the component.

Here's what a stateless component looks like in React.

import React from 'react'

function Button(){

    function someFunction(){
        //...some code
    }

    return <button onclick={someFunction}>Click Me</button>
}

export default Button;
Enter fullscreen mode Exit fullscreen mode

Pretty simple.

But now lets convert this to a stateful component by incrementing a number inside the button whenever it's clicked.

Prior to React 16.8... this is how you would do it.

import React from 'react';

class Button extends React.Component{
    constructor(){
        super();
        this.state = {
            counter = 0;
        }

        this.increment = this.increment.bind(this)
    }

    increment(){
        this.setState({
            counter = this.state.counter + 1;
        })
    }

    render(){
        return (
            <button onClick={this.increment}> 
                {this.state.counter} 
            </button>
        )
    }
}

export default Button;

Enter fullscreen mode Exit fullscreen mode

As you can probably see

There's quite a bit of boiler plate code including somewhat unnecessary lines like

this.increment = this.increment.bind(this)

Which can lead to a lot of code pollution as the project gets bigger 😤


Hooks to the rescue 😌

So we need to change this class component (called Button) into a new functional component using React's hook implementation.

Enter the useState hook. 💥

useState Hook

The useState hook is a function that takes in one optional parameter and returns two values.

The optional parameter is the initial state.

The returned values are,

  1. The State Variable
  2. The setState function for that state variable

in the form of a destructured array.

It looks like this.

const [stateVariableName, setStateVariableName] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode

So how do we create a functional component?

Using the stateful component made using the class component from before

  1. Lets start by importing React and the useState hook at the top of your file.

    + import React, {useState} from 'react'
    +    
    
  2. Then we write a functional component like we did in the earlier stateless component and return a simple button component

    import React, {useState} from 'react'
    +
    + function Button(){
    +     return <button></button>
    + }
    
  3. Then we created the state variable. Using the below method

    Alt Text

    import React, {useState} from 'react'
    
     function Button(){
    +
    +    const [counter, useCounter] = useState(0);
    +
        return <button></button>
    }
    
    
  4. We then attach the counter state as the label for the button

    import React, {useState} from 'react'
    
     function Button(){
    
        const [counter, useCounter] = useState(0);
    
    -   return <button></button>
    +   return <button> {counter} </button>
     }
    
    
  5. And finally we created and attached the increment method and used the setCounter function to update the state

 function Button(){
    const [counter, setCounter] = useState(0);

+   function increment(){
+       setCounter(counter + 1);
+   }
+
-   return <button> {counter} </button>
+   return <button onclick={increment}> {counter} </button>
 }
Enter fullscreen mode Exit fullscreen mode

That's It !!🔥🔥🔥

So what have we done ??

  1. We've removed the use of the this keyword
  2. We've removed a bunch of boiler plate for binding functions and state.
  3. We've essentially made our code more clean and concise.

Now what?

Well for now, you can read about the useState hook from Reacts Documentation

Or

You can go read my article about the useEffect Hook. (To be made)

Top comments (0)