As you know that the state & lifecycle features are used only inside the class component. If you need to use these features inside the functional component then you will have to learn the React Hooks.
You should read this complete tutorial because You will learn everything related to hooks such as useState(), useEffect() & creating your own custom hooks with some examples.
Learn Also –
React Class & Functional Components
Hooks in React Js
React Hooks are just functions that provide useful features to use the state & lifecycle inside the functional component.
If you need to create your applications without using the class component then you will have to use Hooks.
The Hooks are introduced in React version 16.8.
When to use Hooks –
- When you need to create fully functional-based applications.
- When you need to use the state inside the function component.
Important Points –
- You must call hooks only from the top positions of functional components or custom hooks
- You should not call hooks from the normal javascript functions.
- Hooks will not work within the for, while, do-while loops, if-else, if-else if-else, switch conditions, nested custom functions and any other loops &conditions
- Hooks will not work inside class components
Built-in Hooks in React Js
There are two types of built-in hooks that are defined in react js such as –
- useState Hook
- useEffect Hook
Now, let’s know the concept of these both hooks from the next step –
useState Hook
The useState hook is a built-in function that provides feature to add state inside functional components
The useState hook returns an array with two values first is the current state and the second is a function that can be used to update the current state
Syntax –
useState("stateValue");
You can assign the useState hook like this
[stateName, setStateName] = useState("StateValue");
Where –
- stateName will give the value of the state
- setStateName will give a function to update the state
Important Points –
- You can pass only a single value to the useState() as the first parameter only
- You can access values of the useState within the Event Handler or other places where you need it
- useState() can accept strings, numbers, booleans, arrays, objects, and any combination of these
- You can call the useState() multiple times inside the functional component.
Steps to Use useState Hook
1. Import useState from the React like
First of all, You will have to import useState from the React otherwise It will not work.
import { useState } from "react";
2. Call useState() to inilialize state
Now, You must call useState at the top position of functional component.
function FunctionalComponent(){ let [name, setName]= useState("Noor Khan"); let [rollNumber, setRollNumber]= useState(204); let [course, setCourse] = useState({lang:"React hs", topics:40, duration:"3 Months"}); }
3. Acess values of useState()
If you have to update the value of the state then you will have to use an event handler,
Suppose I have created an event handler with the name updateDeveloper and It will execute while you click the button
function updateDeveloper(){ setName("Rapsan Jani"); setRollNumber(501); }
You can access the value of state directly anywhere like
<> <p>Develope Name is: {name}</p> <p>Develope Name is: {rollNumber}</p> <h3> Course Detail</h3> <p>Language: {course.lang}</p> <p>Total Topics: {course.topics}</p> <p>Total Duration: {course.duration}</p> </>
Example –
File Name – Developer.js
import { useState } from "react"; import { useState } from "react"; function Developer(){ let [name, setName]= useState("Noor Khan"); let [rollNumber, setRollNumber]= useState(204); let [course, setCourse] = useState({lang:"React hs", topics:40, duration:"3 Months"}); function updateDeveloper(){ setName("Rapsan Jani"); setRollNumber(501); } return( <> <p>Develope Name is: {name}</p> <p>Develope Name is: {rollNumber}</p> <h3> Course Detail</h3> <p>Language: {course.lang}</p> <p>Total Topics: {course.topics}</p> <p>Total Duration: {course.duration}</p>
<button onclick={developerUpdate} </> ) } export default Developer;
File Name – App.js
import React from "react" import Developer from "./Developer"; function App(){
return <Developer />
} export default App;
useEffect Hook
The useEffect hook is a built-in function that provides a feature to perform side effects like fetching data & updating the DOM directly inside functional components.
Syntax –
useEffect(functiona, array);
Where –
- function – It is the first parameter that will run after before or after rendering. This means that You can pass your own custom function.
- array – It is the second argument that is an option. Even It is used to apply conditions.
Important Points –
- You can pass only two arguments to the useEffect(), the First argument must be a function and the second argument must be an array.
- In useEffect(). You can perform functionality to fetch data, call other imperative API & set the document Title
- You can call the useEffect() multiple times inside the functional component.
- The useEffect runs in both cases before initial render and after each update
Steps to Use useEffect Hook
1. Import useEffect from the React like
First of all, You will have to import useEffect from the React otherwise It will not work.
import { useEffect } from "react";
If you have to use both useState & useEffect hook then you can write code like –
import { useState, useEffect } from "react";
2. Call useEffect() hook
Now, You must call the useEffect inside the functional component.
function FunctionalComponent(){ useEffect(()=>{ console.log("useEffect had been called"); }) }
Example –
Now, Let’s understand the concept & work on the useEffect with this example.
To see the usage of the useEffect, I am going to create an increment & decrement number on the button click.
File Name – Tool.js
import {useState, useEffect} from "react"; function Tool(){ let [incNum, setIncNum] = useState(0); let [decNum, setDecNum] = useState(10); let incNumber(){ setIncNum(incNum+1); }; let function decNum(){ setIncNum(decNum-1); } useEffect(function(){ console.log("useEffect was called"); }, [incNum]); return( <> <h3>{incNum}</h3> <h3>{decNum}</h3> <button onclick={incNumber}> +</button> <button onclick={decNumber}> +</button> </> ); }
export default Tool;
File Name – App.js
import React from "react" import Tool from "./Tool"; function App(){ return <Tool /> } export default App;
Custom Hooks in React Js
Custom hooks are regular javascript functions that can be reused in the multiple components to share a common logic.
In Simple words, If you have to share something common logic between one or more components, then you should create a custom hook.
You can create a custom hook to perform form handling, animation, timers & other functionality.
Syntax –
Creating custom hook like
function useCustomHooksName(){ // Write logic here }
Calling custom hook like
const variableName= useCustomHooksName();
Important Points –
- You must custom hook by adding use word at the begining of its Name.
- You can return anything like string, number, boolean, array, object & other data.
- You can also call useState hooks & other hooks inside the custom hook.
- Even You can define other regular javascript functions inside the function
Example –
File Name – CustomHook.js
import {useState} from "react"; useNumberCounter(){ let [num, setNum]= useState(0); let incNum() =()=>{ setNum(num+1); }; return {num, incNum}; }
File Name – App.js
import React from "react"; import useNumberCounter from "./CustomHook"; function App(){ let data = useNumberCounter(); return( <> <h3>{data.num}</h3> <button onclick={data.incNumb} > +</button> </> ); }