Blog
Our experience of using React Hooks and what you can learn from it!
DATE:
Our experience of using React Hooks and what you can learn from it!

React JS is now a very popular programming language. React Hooks has unlocked new capabilities and allows you to create great applications. It allows one to write very compact code. We share our experience of how we have used React Hooks. We assume here that you have some React Programming knowledge.

React Hooks are functions that allow you to hook into React lifecycle and state features. They primarily serve as an alternative for classes. They can help in keeping your components clean and perform better. Hooks are a recent  addition in React version 16.8.0.

In this article, we are going to show you how to convert a React class into a functional component using the useState Hook.

Hooks don’t work inside classes because they let you use React without classes. We will use the built-in hooks instead of React lifecycle methods. Eg. useState, useEffect, useRef etc.

We are covering useState, useEffect, useRef React hooks in this article. useState() is used to replace the constructor functions and state declarations. While useEffect() is used to replace componentDidMount() and componentDidUpdate(). You can use useEffect as many times as you need to in single component. And the last one, useRef has another cool usage besides DOM refs, it is also a generic container whose current property is mutable, it also can hold any value similar to an instance property of a class.

Steps to convert a React class component into a functional component using React Hooks –

React Hooks

Step 1. Change ‘class ComponentName extends Component’ With ‘function ComponentName(props)‘

Step 2. Remove “this.” And “this.state” from the entire component.

Step 3. import React, { useState } from ‘react’

Step 4. Remove the constructor. Add its logic as shown above in the image for initializing the state variables with the help of useState hook.

Let’s understand conversion into useState, useEffect and useRef with examples –

  • useState() Hook –

The parameter of the useState hook is the initial value of the state. This hook provides the array with two values – the first is the name of the state and the second is the function name which updates the value of that state.

Eg.

const [num, setNum] = useState(0); //declaration

setNum(10) //use

Here num is the state name, setCount is the function that you can use anywhere in the component to update that state.

Here are some examples of setting or initializing state variables for different data types –

//Set an Integer

const [num, setNum] = useState(0);

setNum(10);

 

//Set a String

const [name, setUsername] = useState(‘John’);

setUsername(‘Smith’);

 

//Set a Boolean

const [isValid, setIsValid] = useState(false);

setIsValid(true);

 

//Set and Array

const [items, setItems] = useState([]);

setItems([0,1,2,3,4]);

setItems([{id:0, color:”red”},{id:1, color:”green”},{id:2, color:”blue”}]);

 

//Set and Object

const [form, setValues] = useState({

id: 0,

firstName: ‘’,

lastName: ‘’,

subscribe: false

})

 

setValues({

…form,

firstName: ‘Jamie’,

subscribe: true

})

 

 

  • Replace lifecycle methods (compentDidMount, componentWillUnmount,

 componentWillReceiveProps, componentDidUpdate) with useEffect

 

e.g.

const [items, setItems] = useState([]);

const [num, setNum] = useState(0);

 

  1. compentDidMount

 

useEffect(()=>{

setItems(items);

}, [])   // Here empty array indicates don’t look for any updates

 

b.componentWillUnmount

 

useEffect(()=>{

return () => {console.log(‘unmounting the component’)}

},[])

 

c. componentDidUpdate/componentWillReceiveProps

This will get executed when your ‘num’ state variable and ‘id’ props will get updated.

 

useEffect(()=>{

if (!isEmpty(num))

{

console.log(‘num changed = ’,num);

setItems(items);

}

 

if(!isEmpty(props.id))

{

console.log(‘props.id changed = ’,props.id);

}

},[num, props.id])

 

 

  • Use of useRef

 

const [num, setNum] = useState(0);

const prevNumRef = useRef();

useEffect(()=>{

prevNumRef.current = num;

})

const prevNum = prevNumRef.current;

return <h1>Current value : {num}, previous value = {prevNum}</h1>

 

Advantages

1.With React hooks, the component will be cleaner and easier to read (fewer lines of code). Hooks are easier to work with and to test.

2.It is easy to make code reusable. They don’t create another element in DOM like HOCs in React do.

3. useState – it allows to update different states with specific functions. The ability to move the state update logic as a separate hook.

 

Disadvantages

1.useEffect hook allows to merge three lifecycle methods such as componentDidMount, componentWillUnmount and componentDidUpdate into one and the issue with useEffect is the second parameters ,i.e. the array that we need to pass to define this behaviour. It is not explicit enough.

2.React Hooks are new additions to React. So to convert and test a complex class can be a time-consuming task initially .

3.Since it is relatively a new addition it may not be compatible with all third party libraries. But this is rapidly changing .

This is all about React Hooks in a nutshell. If you are looking to build any a mobile or web application using React technology, then please contact us.

Happy coding!


TAGS:


Leave a Reply

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

MetaSys Software
Contact Contact