DEV Community

sasi kiran
sasi kiran

Posted on

React Hooks Complete Guide | useState() | useEffect() | Rules for React Hooks

React Hooks are the new features released in React 16.8. With Hooks, we can extract stateful logic from a component that can be tested and reused independently. Hooks allow us to use stateful logic without changing our component hierarchy.

The Basic Comparison between Class Component and functional component using React Hooks.

Class Component:
In class component, we have state property to define a local variable that can be accessed only in the class or which can be passed as props value to the child component. We have component lifeCycle methods to classes to handle the sideEffects (fetching data from API, DOM manipulation).

Example of a simple class component.

import React, { Component } from "react";

class ExampleUsingClass extends Component {

constructor(props) {

super(props);

this.state = {

 count: 1
Enter fullscreen mode Exit fullscreen mode

};

}

handleIncrement =() => {

const { count } = this.state;

this.setState({

 count: count + 1
Enter fullscreen mode Exit fullscreen mode

});

}

render() {

return (

 <div>

   <p>

     Count Value : <span>{this.state.count}</span>

   </p>

   <buton onClick={this.handleIncrement}>Increment</buton>

 </div>
Enter fullscreen mode Exit fullscreen mode

);

}

}

export default ExampleUsingClass;

In the above example, we have defined a count variable in the state and we are changing the count on the Increment button click.

Example using React Hooks:

import React, { useState } from "react";

function ExampleUsingHooks() {

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

return (

 <p>

   Count Value : <span>{count}</span>

 </p>

 <buton

   onClick={() => {

     setCount(count + 1);

   }}

 >

   Increment

 </buton>

);

}

export default ExampleUsingHooks;

Above is an example of the same component using React Hooks. For a better understanding of react Hooks concept, Please read further.

The Basic Concept of React Hooks.

  1. useState().

In the earlier version of React, the functional components had no state. Now, from React 16.8 functional components can also have state with the help of Hooks by using useState() method.

Below is the syntax for declaring a state variable in functional component

const [age, setAge] = useState(20);

Here, age is the variable name of state. setAge is a function for changing the value of age in a state. We can initialize the state passing initial value to the useState() method.

The useState() method returns a pair, the current value of the state variable and a function with the help of it we can update the value. We can call this function from anywhere in the component in order to update the value. This function is the same as using this.setState() method in the class component.

We can use React Hooks more than once in a single component.

function declaringMultipleStateWithHooks () {

// Declare multiple state variables!

const [name, setName] = useState('CronJ');

const [mobile, setMobile] = useState(8871887171);

const [address, setAddress] = useState({ street: '#1284, 14th Main Road, 7th Cross Road', landMark: 'Near House of common', city: 'Bangalore', country: 'Bangalore'});

// ...... (other code of component)

}

Updating the state variable in a functional component.

handleName = () => {

setName('CronJ Vision')

}

  1. useEffect() Operations like fetching data from API, setting up subscriptions and manually changing the DOM in React Component are called “side effects” or effects for short as they can affect other components and can’t be done before rendering.

The Effects Hook, useEffect, add the ability to perform side effects from a function component.

It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React Classes.

Using useEffect hook, it tells React that the component needs to do something after render. React will remember the function you passed and call it after DOM manipulation.

Example of useEffect() method:

Step 1 – Defining state in component.

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

function ExampleOfUseEffects() {

// defining state variable

const [name, setName] = useState({ first: "shubham", last: "sharma" });

return (

 <h3>First Name: {name.first}</h3>

 <h3>Last Name: {name.last}</h3>

);

}

export default ExampleOfUseEffects;

Step 2 – using useEffect method in the component

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

function ExampleOfUseEffects() {

// defining state variable

const [name, setName] = useState({ first: "Shubham", last: "Sharma" });

//using useEffect

useEffect(() => {

console.log("calling useEffect");
});

return (

 <h3>First Name: {name.first}</h3>

 <h3>Last Name: {name.last}</h3>

);

}

export default ExampleOfUseEffects;

Using the useEffect as Class lifeCycle methods:

By default, useEffect runs after every successful render. Now useEffect method is behaving like componentDidUpdate method. We can make it conditional when to call effect. We can pass an array as the second argument to useEffect. This array tells the React that just call useEffect whenever fields in the array have been changed.

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

function ExampleOfUseEffects() {

// defining state variable

const [name, setName] = useState({ first: "Shubham", last: "Sharma" });

// it will check if the value of name variable is changed then only it will executed the passed function

useEffect(() => {

console.log("calling useEffect when name variable value is changed");

setName({ first: "Manas", last: "Yadav" });

}, [name]);

return (

 <h3>First Name: {name.first}</h3>

 <h3>Last Name: {name.last}</h3>

);

}

export default ExampleOfUseEffects;

It will only call effect when the value of name is changed.

We can also make useEffect to behave like componentDidMount by passing an empty array as a second argument to the useEffect.

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

function ExampleOfUseEffects() {

// defining state variable

const [name, setName] = useState({ first: "Shubham", last: "Sharma" });

//using useEffect

useEffect(() => {

console.log("calling useEffect only once");

}, []);

// it will execute the useEffect only once.

useEffect(() => {

console.log("calling useEffect as componentDidMount method");

}, []);

return (

 <h3>First Name: {name.first}</h3>

 <h3>Last Name: {name.last}</h3>

);

}

export default ExampleOfUseEffects;

We can also make useEffect to behave like componentWillUnmount method.

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

function ExampleOfUseEffects() {

// defining state variable

const [name, setName] = useState({ first: "Shubham", last: "Sharma" });

// it will executed the useEffect and will return a function which will excute before running useEffect next time or when component ummounts.

useEffect(() => {

console.log("calling useEffect as ComponentWillUnMount method of classes");

return () => {

 console.log("Cleaning up...");
Enter fullscreen mode Exit fullscreen mode

};

}, []);

return (

 <h3>First Name: {name.first}</h3>

 <h3>Last Name: {name.last}</h3>

);

}

export default ExampleOfUseEffects;

useEffect can either return nothing or return a function which is executed in two cases

Before useEffect runs the next time
When the component unmounts.

Rule for React Hooks:
Call Hooks only at the top level. Don’t call hooks in loops, conditions or in nested functions.
Call Hooks only from functional components. Don’t call Hooks from the regular javascript functions.

Conclusion:
React hooks help in improving the design pattern and performance of an application. Class Components are not getting obsolete so one doesn’t need to rewrite Class Based Components using Hooks. I believe you should start using React Hooks in your project too.

Be it a software developer, programmer, coder, or a consultant, CronJ has it all. CronJ has been a trustworthy company for startups, small companies, and large enterprises. Hire the web of experienced React developers for your esteemed project today.

ReactJS Development Services

Top comments (0)