reactjs hook

ReactJs Tutorial: How to use ReactJs Hooks (useState, useEffect)

In react 16.8, it came with a gift to all React developers, i.e., Reactjs hooks. It launched at the React conference in October 2018. In Reactjs hooks, we can use all other ReactJs features without using class. It means we can use state and other React features without writing a class.

It is a fundamental change in which we can move to functional components. It doesn’t mean we should not write previous class components. It’s 100% backward compatible.

At React Conference 2018, Sophie Alpert and Dan Abramov introduced Hooks, you can watch the video introduction below:

What motivated to ReactJs team to introduce this new concept “hooks.”. There were some issues that the ReactJS team decided to introduce this concept. We will briefly describe those concepts lets check those.

1. What is a React Hook?

Hooks are functions that let you “Hook” into the React state and lifecycle features from function components without using class. Hooks don’t work inside the classes. There is no need to rewrite the old react classes. But surely you can use hooks in new code.

Reacts provides few built-in hooks like useState, useEffect, etc. In this article, we will try to understand those few inbuilt hooks.

There are some rules for using the Hooks in ReactJs.

  1. Call Hooks at the top level. Please don’t call reactjs hooks inside the loops, conditions, etc.
  2. Call Hooks from React function components. Please don’t call it from regular Javascript functions.

1. useState Hook

A hook is a particular function that let you hook into the react features. useState is a hook that lets you add React state to the functional components without using classes.

Let’s assume that you are writing a function component, and later you realize that you need to add some state to it. Earlier, we need to convert it to a call. There we can manage the state. After introducing the hooks, we can manage it into the functional components by using the “useStae” hooks.

First, we will see in class how we are managing the state. In class, first, we need to add constructors in the class. After that, we need to initialize the count in this.state to zero( count : 0).
On rendering the component, the initial value of count will be 0.

import React, { Component } from 'react'

class ClassCounter extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             count:0
        }
    }

Now we will see the example using functional components. In this functional component, we have
initialize the state by using the react hook. First, we need to import useState. In functional components, we don’t need to use the “this” variable. There we need to call useState directly inside the functional components.

import React, {useState} from 'react';

function DataFetchingOne() {

    const [loading, setLoading] = useState(true); 
// initial value to true

What does calling useState do?
It declares the state variable. In our case, the count is the variable. Another value is a function to change the count variable.

What do we need to pass to useState as an argument?
In useState we need the only argument need to pass in the initial state. It does’t need to be an object as we do in classes. In our example, we need a number for how many times the user has clicked on the button. We have passed the initial value as 0—the second part is to set a new value for the count variable. If we need two different values in state, we need to call useState() twice.

How to read state in the hooks

In functional components, we can call value directly.

<div> Count - {count}</div>

How to Update State in the functional hooks

First, we will see the example in the class component

 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
  </button>

In functional components, we already have setCount and count as variables. So there we need to call the setCount function.

<button onClick={() => setCount(count + 1)}>
    Click me
  </button>

Example of ReactJs Hooks Snippet using functional components

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Example of above example using class snippet

import React, { Component } from 'react';

class Counter extends Component {

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

    increment(){
        this.setState({
            count: this.state.count + 1
        }, ()=> {
            console.log(this.state.count);
        });
    }
    
    render() {
        return (
            <div>
                <div>count - {this.state.count}</div>
                <button onClick={() => this.increment()}>Increment</button>
            </div>
        )
    }
}

export default Counter;

2. useEffect Hook

useEffect is short for ‘use side effect’. Effects mean when our application reacts with the outside world, like calling an API. It allows us to run a function when there are some changes in the application.

Suppose you have an understanding or familiar with React class lifecycle methods. You can easily understand the useEffect. We can think of useEffect as componentDidMount, componentDidUpdate, and componentWillUnmount like class components. To use useEffect first, we need to import it.

import React, { useEffect } from 'react';

The useEffect() functions to run when the component is first rendered, and on every subsequent, changes it will update. React will first update the DOM. After that, it will call the function passed to useEffect. The useEffect() functions to run when the component is first rendered, and on every subsequent, changes it will update. React will first update the DOM. After that, it will call the function passed to useEffect without blocking the UI rendering. It will help us to make out apps feel faster. We can add multiple useEffect in a single component. Let’s see an example.

import React, { useState, useEffect } from 'react';

function HookMouse() {

    const [x, setX] = useState(0);
    const [y, setY] = useState(0);

    const logMousePosition = e => {
        console.log('Mouse Event');
        setX(e.clientX);
        setY(e.clientY);
    }

    useEffect(() => {
        console.log('Use Effect Called');
        window.addEventListener('mousemove', logMousePosition);
    })

    return (
        <div>
            Hooks X - {x} Y - {y}
        </div>
    )
}

export default HookMouse;

This example is similar to componentDidUpdate lifecycle of a stateful component. Now we will implement all the lifecycle components life cycle in functional components as they are implemented in the Class components.

  1. How to make it work like componentDidMount

Suppose we will pass an empty array in useEffect function as the second parameter. Then it will behave like componentDidMount. Let see an example

const  SpyCoding = (props) => {
   useEffect( () => {
      console.log(‘hello from useEffect call componentDidMount’);
      setTimeout( ()=>{ alert(‘hello Reactjs Hooks’); }, 2000);
   }, [] );
}

We can pass the second argument in the userEffect function. If there are any changes, then only that specific userEffect function will execute. The second argument is an array means we can pass multiple elements inside that array. Let see an example for this

useEffect((props) => {
        Axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
        .then(res => {
            console.log(res);
            // setPosts(res.data);
            setPost(res.data);
        })
        .catch(err => {
            console.log(err)
        })
    }, [props.id])

If there is any changes in the “id” props the userEffect function will be executed.

2. How to do cleanup work in functional component (componentWillUnmount)

Inside useEffect if we will add a return statement at the end of the useEffect function. That return function does the cleanup work. It similar to componentWillUnmount. Let see an example

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

const tick = () => {
   setCount( prevCount => prevCount + 1);
 } 

useEffect(() => {
        const interval = setInterval(tick, 1000);
        return () => {
            clearInterval(interval);
        }
    },[count])

In this example, the count is increasing every second. When we remove that component, the return function will execute the return function. In that, it will clear the setInterval.

If you have used class components with lifecycle methods, we can easily understand that how much it has become optimized by using reactjs hooks. Earlier, we need to use _prevProps or _prevState and compare it with the current. If they do not match, we execute the functionality. Now, in hooks, we need to pass the extra parameter. That will ensure that the hook is run only when the state gets change.

Conclusion

Hopefully, we have learned some basic concepts of the reactjs hooks. If we carefully understand the concepts, we can conclude that hooks are designed to solve most of the problem that class components suffer from. It has been recommended that you gradually shift towards the reactjs hooks.

2 thoughts on “ReactJs Tutorial: How to use ReactJs Hooks (useState, useEffect)”

Comments are closed.