Hooks in React

Posted By :Akshay Singh |27th February 2020

 

 

Hooks in React (React Native + React JS)

 

With the advent of React 16.8, React has brought various new features, APIs & Lifecycles to improve working with React & React Native.

These new features were introduced to standardize the pattern of programming using React, and prevent users to adopt inappropriate methods or anti-patterns which arise due to lack of insight knowledge of basic concepts of Javascript.

With the Facebook’s introduction of React 16.8 in 2018, the React team brought forward the concept of “Hooks.” In this post, we are going to explore the reasons & benefits behind creating & using hooks and how to use them in a React Native/React JS application.

We know, there are 2 ways to create UI components in React:

1. Functional/Stateless components

2. Class/Stateful components.

Usually, we create a class component when we need to maintain a state or to use React lifecycle methods such as (componentDidMount, shouldComponentUpdate) in our UI component. But, in reality, surprisingly, there is no actual class present in React, which means the classes are just syntactic sugar in React to help it look more like the popular OOP classes, and these class components eventually will convert into functional components.

 

6 Reasons why you shouldn’t use Class based/Stateful Components in React:

1. As the UI components grow in size & become huge depending on the nature of application, it gradually becomes difficult to manage and debug the code.

2. There is a lot of boiler plate code that is required to create a single class component.

3. ‘this’ and ‘scope binding’ are confusing in class components.

4. Unused methods inside Class based components are not removed in the minified files.

5. Class components usually make hot reloading difficult.

6. Class based components substantially reduce the capablities of compiler optimization.

In order to overcome these impediments, the React team came up with the Hooks concept.

 

Let’s Hook Up Now

 

The idea behind using hooks in React (Native +JS) is to get the features & capabilities that we get in a class component into a functional component as same. Basically, we have been using Class based components to work with state management & React Lifecycle hooks. Below are examples to show how hooks are used to achieve the two aforementioned class component capabilities.    

 

 import React, {useState} from 'react'

 const ButtonDemo = props => {
 
 const [defaultVal, setDefaultVal] = useState(0);
 
 return (
	<div className="container">
  	  <p>Default value is : {defaultVal}</p>
 	  <button onClick={()=>setDefaultVal(++defaultVal)}/>
 	</div>
  )}
  
  ReactDOM.render(<ButtonDemo/>, document.getElementById('root'));
  

In the example above, we have used a term called useState that has been destructured from the React API. This useState is a hook that helps in the creation of state in a stateless or functional component.

Basically, useState is a method in which we pass an argument & that argument will be treated as the default or initial value of the state variable. If we don’t pass in any arguments, then 'undefined' will be assigned to the state variable.

In the snippet above, value passed to the useState method forms the initial value of the state variable of our component. useState returns a pair of  2 values, 1.) the current state  2.) method to update it.

Here in this code, the current state is defaultVal & it has been initialized to 0, & setDefaultVal  is the method to alter the value of defaultVal 

 

Lifecycle Methods With Hooks

 

To use React component lifecycle methods inside a functional component, React provides us a hook called useEffectuseEffect hook has the same functionality as componentDidMount, componentDidUpdate, and componentWillUnmount. Let’s have a look at some examples to understand the usage of useEffect hook:

   
 
 import React, {useState,useEffect} from 'react';
 
 const ButtonDemo = props => {
 const [defaultVal, setDefaultVal] = useState(0);
 
 useEffect(()=>{
 document.title= `You have set the value to ${defaultVal}`;
 });
      
 return (
 <div className="container">
 <p>Default value is : {defaultVal}</p>
 <button onClick={()=>setDefaultVal(++defaultVal)}/>
 </pre>
 </div>
 )}
 
 ReactDOM.render(<ButtonDemo/>, document.getElementById('root'));


In the above example, we can observe that we have de-structured ‘useEffect’ from the React API in the same manner as ‘useState’.

Here, useEffect runs every time the button is clicked & updates the document title with updated value of defaultVal.

  • useEffect when used without second parameter, as used in example above, has the same behaviour as render() lifecycle method of a Class based Component.
  •  useEffect when used with empty array [ ] as  second parameter, behaves like componentDidMount() & componentWillUnmount() lifecycle method of a Class based Component.
  • useEffect when used with a prop or state variable within brackets such as , [defaultVal] as second parameter, will cause the component to re render only if there is a change in value of that value which has been passed in second argument within brackets. 

Below is an example to demonstrate different uses of useEffect hooks & useState to add functionality to UI Component.

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

 const App = props => {

 const [defaultVal, setDefaultVal] = useState(0);
 const [users, setUsers] = useState([]);
 const [message, setMessage] = useState("");
 const [error, setError] = useState("");

 useEffect(()=>{
 document.title = `You have set the value to ${defaultVal}`;
 });

 useEffect(() => {
 axios.get(' http://dummy.restapiexample.com/api/v1/employees')
 .then(res => {
 setUsers(res.data);
 })
 .catch(err => {
 setError(err.message);
 })}, []);

 useEffect(()=>{
 if(users.length>0){
 setMessage("Fetched Users Successfully");
 }},[users]);

 return (
 <div className="container">
 <p>Default value is : {defaultVal}</p>
 <button onClick={()=>setDefaultVal(++defaultVal)}/>
 <ul>
 {
  users.map(item=> <li>{item.employee_name}</li>)
 }
 </ul>
 <p>{message}</p>
 {error && <p>{error}</p>}
 </div>
 )}
 
 ReactDOM.render(<App/>, document.getElementById('root'));


Conclusion

From these examples we can conclude we are able to reframe our class components as functional components & , in the future, hooks will be used more and more in React projects.

 


About Author

Akshay Singh

Akshay is a talented Front end developer, He always keeps himself ahead in embracing and adapting new technologies & best practices. He is specialized in React Native Hybrid app development

Request For Proposal

Sending message..

Ready to innovate ? Let's get in touch

Chat With Us