Effect Hook and Rules of Hooks

 

1. Effect Hook

React provides a built-in hook called

useEffect
that allows executing logic after the component render

In general this

useEffect
hook can be simply called as Effect hook

Using Effect Hook we can perform actions like,

  • Making API Call
  • Using Scheduler methods like setInterval( )
  • DOM Manipulations, etc.

Syntax:

useEffect(effect);
JSX

The

useEffect
accepts effect as an argument, where the effect is a callback function

1.1 Updating Browser title using Effect Hook

Using the title property provided by the DOM object we can update the Browser title

Import the

useEffect
from the
react
and call it inside the component

File: src/components/Scoreboard/index.js

import {useState, useEffect } from 'react'
...
const Scoreboard = () => {
const [score, setScore] = useState(0)
useEffect(() => {
document.title = `Score: ${score}`
})
...
return (
...
<ScoreText>{score}</ScoreText>
...
)
}
export default Scoreboard
JSX
Collapse
  • React keeps track of the effect and executes it after the render

  • All the state variables and props are accessible to the Effect

  • If you try to pass arguments to effect and access them, you'll get undefined values

useEffect((score) => {
document.title = `Score: ${score}`
})
JSX

1.2 Accessing State values

If you access the new state value immediately after updating the state in Event handlers, you may not get the updated value because state updates are asynchronous

const onIncrement = () => {
setScore(prevScore => prevScore + 1)
document.title = `Score: ${score}`
}
JSX

Use Effect Hook, if you want to access new state values immediately after updating the state

useEffect(() => {
document.title = `Score: ${score}`
})
JSX

2. Rules of Hooks

While writing/using the hooks you should follow the below rules,

  • Rule 1: Hooks should be called only at the top level
  • Rule 2: Hooks should be called only inside React Function Components and Custom Hooks

React provides the eslint-plugin-react-hooks package that throws errors if we don’t follow these rules

3. Scoreboard Application Code

Use the below command to get the Final Code for Scoreboard Application

ccbp start RHSIVRZE65
SHELL

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form