DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on • Updated on

React Hooks

Hooks
Image description

Why Hooks

Image description

Image description

Image description

Hook Rules
Image description

Syntax

Image description

In a hook -> A state variable can be ->

  1. A number
  2. A string
  3. Boolean
  4. Object
  5. Array

If we have use dan object as set state and modified a part of it and then some other part it doesn't merge them and update but updates them independently and so they are rendered on screen as different entities so to rule that out we us ethe spread operator to give the whole object value first and then modify a part(s) of it.

Image description

Hooks with Arrays

Image description

Things to remember while dealing with hooks

Image description

useEffect

Image description
It is basically whenever the component renders or update in rendering on screen this useEffect() gets triggered and what we define under this is what function we want to trigger. Here we have defined an arrow function.

In a class component

A simple condition will help us to not re-render unnecessarily.

Image description

Similarly with Functional Components

We can use useEffect() to do the same by adding the state or prop to be checked if it has updated or not if it's not then useEffect() isn't executed.

Image description

How to mimic ComponentWillUnmount() in a Functional Component
With the help of removeEventListener()

Image description

Tick in Hooks
To mention the state variable that we need to re-render needs to be mentioned in the dependency array (a.k.a the array that is passed to useEffect()). This is how we re-render specific state variables.

Image description

OR
By using state variable's prevState to update the new state and re-render it on screen.
Image description

Multiple useEffect to group the data
This groups relevant data together and use multiple useEffect -> Notice how we have a state variable declared and a corresponding useEffect for it. This solve the problem of "relevant data far apart" in CLass Components

Image description

Context

Defining context in parent component

Using context in child component

Image description

Shortcut for using context

Top comments (0)