A quick guide to react hooks

With the release of React 16.8, hooks were introduced. The main reason to introduce hooks was to solve the problem of State and other important features which were missing in the functional components. Let’s get into more details why do we need Hooks?

WHY HOOKS?

While writing a complex code, we need stateful components to store the logic inside. Which causes large components which are hard to breakdown further into small components.

There can be cases, like as animation or data fetching, which can have a small functional component of their own if we can provide some kind of state to it.

Using the hooks, we can solve this problem. It helps us use state inside of a functional component.

It also gives us a better way to deal with complex codes instead of using cumbersome patterns like as

  1. Rendering props
  2. Higher order components

HOW TO USE HOOKS?

Let’s take an example. A counter app like this, which increase the value based on the click.

A counter app

The way we code it with the class component is as follows:

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      value: 0
    }
  }

  handlePress = () => {
    this.setState({ value: this.state.value + 1 })
  }
  
  render(){
  return (
    <div className="App">
    Counter : {this.state.value}
    <div>
      <button onClick={this.handlePress}>Increase</button>
    </div>
    </div>
   
  );
  }
}

But with the use of hooks, we can reduce the code to many lines.

useState()

we are going to use the useState() hook here. It provides us an array which contains state and a function to update that state.

useState hook

Just import useState from react. and change the class component to the functional component like below.

import React, { useState } from 'react';
import './App.css';

const App = () => {
  const [ value, setValue ] = useState(0);
  return (
    <div className="App">
    Counter : {value}
    <div>
      <button onClick={() => setValue(value + 1)}>Increase</button>
    </div>
    </div>
   
  );
}

export default App;

Easy right?

We can use more than one hooks in a component. So to have more state variables either have an object inside useState() . or use multiple useState() hooks. It will work just as fine.

useEffect()

By using useState() , we understood how to make functional component stateful. What if we need to add some logic as well to that functional component?

Here useEffect() comes into play.

useEffect() serves the same purpose as the componentDidMount, componentDidUpdate & componentWillUnmount all merged in a single API.

Let’s take an example where we want to change the title of the web page based on the value of the counter. We just need to add this much code to our file.

import React, { useState, useEffect } from 'react';
..
useEffect(() => {
    document.title = `the number is ${value}`;
  })

By default, React runs the effects after every render. But what if we want to run the effect at a particular time, or on the basis of some particular state variable change?

In that case, we will provide second argument to the useEffect() hook in the form of an array. This array would constitute the values which needs to be changed in order to run the effect again.

For example,

useEffect(() => {
     document.title = the number is ${value};
   }, [value])

This hook will run only when the ‘value’ will be changed.

There would be some cases where we want to run the effects only once just like as componentDidMount. In that case use [] as argument.

Using these hooks, the complexity of code can be reduced to a great extent.

Hope you enjoyed this blog and learnt something new today!!!

WHAT NEXT?

Hooks also provide a great way to create our custom hooks.

Excited about it? You can read about it here.

Or wait till i post my another blog about custom hooks. If you are interested in that, Please subscribe to the blog. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *