Managing Component Life Cycle in React
React provides many built-in hooks for Managing Component Life Cycle in React
What exactly is a hook in React?
Hook is a special function in React which “hooks into” special React feature. Let’s discuss few such hooks with examples:
A] useState Hook:
Every React component can have its own state. What do we mean by state? The state is the set of data that is managed by the component.
For example. Each individual input element of the form is responsible for managing its state: what is written inside it. A button is responsible for knowing if it’s being clicked, or not. A link is responsible for knowing if the mouse is hovering over it.
In React, all our applications make heavy use of components’ states. We manage state using the useState hook in React. It’s technically a hook.
You need to import useState hook from React library:
import { useState } from ‘react’
Calling useState() , you will get back a new state variable, as a function that we can call to alter its value. useState() accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state.
const [count, setCount] = useState(0)
This is important. We can’t just alter the value of a state variable directly. We must call its modifier function. Otherwise, the React component will not update its UI to reflect the changes of the data. Calling the modifier is the way we can tell React that the component state has changed. Master React JS course in Pune. Start building dynamic web applications. Enroll now for a brighter web development career. The syntax is a bit weird, right? Since useState() returns an array we use array destructuring to access each individual item, like this:
const [count, setCount] = useState(0)
Here’s is an example:
import { useState } from ‘react’
const Counter = () => {
const [count, setCount] = useState(0)
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button> </div>
)
}
For Free Demo classes Call: 8237077325
Registration Link: Click Here!
You can add as many useState() calls you want, to create as many state variables as you want:
const [count, setCount] = useState(0)
const [anotherCounter, setAnotherCounter] = useState(0)
Let’s look into another hook
B] useEffect Hook:
This hook allows components to have access to the lifecycle events of a component. When you call this hook, you pass it a function. The function will be run by React when the component is first rendered, and on every subsequent re-render or update. React first updates the DOM, then calls any function passed to useEffect() .All without blocking the UI rendering even on blocking code.
Example:
import { useEffect, useState } from ‘react’
const Counter = () => {
const [count, setCount] = useState(0)
useEffect(() => {
console.log(`You clicked ${count} times`)
})
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button> </div>
)
}
Since the useEffect() function is run on every subsequent re-render/update of the component, we can tell React to skip it, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes. useEffect is run once when the component finishes loading for the first time, and then every time the component state is updated.
useEffect(() => {
console.log(`Hi ${name} you clicked ${count} times`) }, [name, count])
Similarly, you can tell React to only execute the side effect once (at mount time), by passing an empty array:
useEffect(() => {
console.log(`Component mounted`)
}, [])
Let’s discuss another useful hook
C] useRef Hook:
This hook returns an object that you can use during the whole lifecycle of the component. The main use case for the useRef hook is to access a DOM child directly. Usually it is used when you reference a value that’s not needed for rendering.
Import it from react library
import {useRef} from ‘react’
A ref changing value doesn’t trigger a re-render. This one is often a tricky one, and trips a lot of developers! It is the opposite behavior of what happens when using useState.
For Free Demo classes Call: 8237077325
Registration Link: Click Here!
const ref = useRef();
You can optionally initialize it with a default value by passing it as an argument to the useRef hook: const ref = useRef(0);
For Example:
import {useRef} from ‘react’
const CountRef = ()=>{
const ref = useRef(0)
const handleClick = ()=>{
ref.current = ref.current + 1;
console.log(ref.current)
}
return (
<div>
<button onClick={handleClick}>{ref.current}</button> </div>
)}
Another important use of useRef hook is to access DOM API Directly
In below example, whenever button is clicked, input element is focused by calling DOM API focus()
import { useRef } from “react”;
const Input = ()=>{
const inputRef = useRef()
const handleClick = ()=>{
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} />
<button onClick={handleClick}>Focus</button>
</div>
)}
Let’s have discussion on another important hook:
D] useContext Hook:
If you want to share the data deep in the component tree (hierarchy), then you need useContext hook
Need to import it from react library
import {useContext} from ‘react’
To use it properly below steps need to be implemented in your react app
Step 1:
Create context
To create the context, import createConext from react library
import createContext from ‘react’
Then globally create your context object
const MyContext = createContext()
Optionally you can provide initial value
const MyContext = createContext(“Hello World”)
Step 2:
In Parent Component, use Context Provider in the form of JSX and store the required data in context using it’s value attribute
Surround the child component by using Context Provider
<MyContext.Provider value={someValue}>
<ChildComponent/>
</MyContext.Provider>
Example:
import {useState} from ‘react’
import Component2 from ‘./Component2’;
import { createContext } from ‘react’;
export const ComponentContext = createContext()
const Component1 = ()=>{
const [name,setName] = useState(”)
return (
<div style={{border: ‘3px solid black’}}>
<h1>Component1</h1>
<label>Enter your name
<input value={name} onChange={(e)=>setName(e.target.value)} /> </label>
<ComponentContext.Provider value={name}>
<Component2 />
</ComponentContext.Provider>
</div>
)
}
Step 3:
Subscribe to the context and access the value stored in context using hook useContext() Any child component deep in the component tree should subscribe to the context by calling hook useContext(context)
For Free Demo classes Call: 8237077325
Registration Link: React JS Classes in Pune!
Example:
import { useContext } from “react”;
import { ComponentContext } from “./Component1”;
const Component4 = ()=>{
const name = useContext(ComponentContext)
return (
<div>
<h4>Component4</h4>
<h4>Name is {name}</h4>
</div>
)
}
Do visit our channel to explore more: Click Here
Author:-
Dharamraj Pawale
Call the Trainer and Book your free demo Class For ReactJS Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.