Hooks In React

Introduction
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
So in simple terms, they are functions but have some inbuilt powers in them
How to identify hooks?
- Any function which starts with use ---- is said to be an hook
Inbuilt hooks in React useState()
useState():
Why to use this hook: the problem with using normal variables in react is as we render the page all the variables get initialized back to their original state
It declares a “state variable”. Our variable is called
countbut we could call it anything else, likebanana. This is a way to “preserve” some values between the function calls —useStateis a new way to use the exact same capabilities thatthis.stateprovides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.
Syntactically writing a useState()
import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
Explanation of the code snippet
The useState is inbuilt but we have to make a named import to use it
hence we do:
import {named_import } from 'react'setcount is a setter method to set the value of count we can only do this by using the set count
useState(0) --- the parameter passed to initialize the count variable to default as 0
Another important thing to note is it should be used in those functional components in which the state needs to be saved
Can we use normal variables?
The answer is yes we can but while making its use we have to make sure it is not a value that we are using somewhere else re-rendering
Because those values will not be retained when we do so
UseEffect API
The whole crux behind using useeffect is the reconciliation algorithm of react
What the reconciliation algorithm does is it will re-render only those components whose state has changed
We can make api calls using the browser api fetch()
The problem with fetch is that suppose we have written it inside a functional component. Now as soon as we make api calls and we change something, react will re-render that entire component and fetch will be called again ,this will now reduce the perfomance of react
Hence we use useeffect
The
useEffectHook allows you to perform side effects in your components.Some examples of side effects are: fetching data, directly updating the DOM, and timers.
useEffectaccepts two arguments. The second argument is optional.useEffect(<function>, <dependency>) //dependency is an arrayWhen the dependency array is empty then the callback/function passed in useEffect is called only when after the components are rendered that too only once
When we have some thing passed in the array then every time the the variable passed in the array changes , the the callback function passed in the useEffect will be called