React Hooks

Level : Intermediate
Mentor: Shailendra Chauhan
Duration : 00:02:00

Why Hooks?

Hooks revolutionized React by allowing developers to use state and lifecycle features in functional components without needing class components. This leads to cleaner, more concise code.

Hooks Allow Us To

Hooks provide a way to manage state, perform side effects, and work with lifecycle methods in functional components, making it easier to write and maintain React applications.

Rules for Using Hooks

Hooks should be used only within functional components and always at the top level. This ensures that Hooks are called consistently in the same order during each render.

Common Mistakes to Avoid

One common mistake is calling Hooks conditionally, leading to unexpected behavior.

Example

if (condition) {
 useState(initialValue);
}

The State Hook

The `useState` Hook lets you add state to functional components.

Example

import React, { useState } from 'react';
function Counter() {
 const [count, setCount] = useState(0);
 return (
   <div>
    Count: {count}
    <button onClick={() => setCount(count + 1)}>Increment</button>
   </div>
  );
}

State Setter Callback Function

When updating a state based on the previous state, a callback function is recommended to ensure accurate updates.

Example

setCount(prevCount => prevCount + 1);

Multiple State Hooks

You can use `useState` multiple times in a component to manage different pieces of state separately.

Example

const [name, setName] = useState('');
const [age, setAge] = useState(0);

Side Effects

Side effects like data fetching or interacting with the DOM can be performed using the `useEffect` Hook.

Example

import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch data and update state
fetchData().then(result => setData(result));
}, []);
return <div>{/* Render data here */}</div>;
}

The Effect Hook

The `useEffect` Hook is used to manage side effects. It runs after each render and can be configured to run only when specific dependencies change.

Example

useEffect(() => {
// Code to run after each render
}, [dependency]);

Effect Cleanup Functions

The cleanup function returned by `useEffect` is used to clean up any resources, like event listeners, to prevent memory leaks.

Example

useEffect(() => {
 const eventListener = addEventListener('click', handleClick);
 return () => {
  removeEventListener('click', handleClick);
 };
}, []);

Multiple Effect Hooks

You can use `useEffect` multiple times in a component to manage different side effects separately.

Example

function Timer() {
 useEffect(() => {
  const interval = setInterval(() => {
   // ...
  }, 1000);
  return () => {
   clearInterval(interval);
  };
 });
 useEffect(() => {
  // Another effect...
 });
 // ...
}  

Effect Dependency Array

The dependency array in `useEffect` specifies when the effect should be re-run. If empty, the effect runs only after the initial render. If dependencies are provided, it runs whenever they change.

Example

useEffect(() => {
  // Code to run when dependencies change
}, [dependency]);
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this