React Hooks
React Hooks
Introduction
Hooks are a new addition in React 16.8. They let you use state and
other React features without writing a class component.
useEffect: To manage side-effects like API calls, subscriptions, timers, mutations, and
more.
useRef: It returns a ref object with a .current property. The ref object is mutable. It is
mainly used to access a child component imperatively.
useState hook
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect hook
The data fetching, subscriptions, or manually changing the DOM
operations from React components before.
We call these operations “side effects” (or “effects” for short) because
they can affect other components and can’t be done during rendering.
The Effect Hook, useEffect, adds the ability to perform side effects from
a function component.
• So calling any native Web APIs will be considered as a side effect as it’s
not within the React universe
• We usually manage React side effects inside the useEffect hook (part of
the React Hooks API)
useEffect
What does useEffect do? By using this Hook, you tell React that your component needs to do
something after render.
React will remember the function you passed (we’ll refer to it as our “effect”), and call it later
after performing the DOM updates.
import { useState, useEffect } from "react";
export default function Timer() {
const [count, setCount] = useState(0);
// useEffect(() => {
// setTimeout(() => {
// setCount((count) => count + 1);
// }, 1000);
// },[]);
We should always include the second parameter which accepts an array. We can
optionally pass dependencies to useEffect in this array.
1. No dependency passed:
useEffect(() => {
//Runs on every render
});
3. Props or state values:
2. An empty array:
useEffect(() => {
useEffect(() => { //Runs on the first render
//Runs only on the first render //And any time any dependency value
}, []); changes
}, [prop, state]);
useEffect
useEffect Hook that is dependent on a variable. If the count variable updates,
the effect will run again:
function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);
useEffect(() => {
setCalculation(() => count * 2);
}, [count]); // add the count variable here
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
Effect Cleanup
Some effects require cleanup to reduce memory leaks.
Timeouts, subscriptions, event listeners, and other effects that are no longer needed
should be disposed. We do this by including a return function at the end of the useEffect
Hook.
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);