0% found this document useful (0 votes)
29 views19 pages

Powerful ReactJS Hooks 1727339763

Uploaded by

Swa Buk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views19 pages

Powerful ReactJS Hooks 1727339763

Uploaded by

Swa Buk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

POWERFUL

REACTJS
HOOKS
HOOKS
Unlock the power of React Hooks
to write expressive, concise, and
high-performance components.

By: Minal Sontakke


Table
of Contents
I. Introduction 3

II. useCallback Hook 4

III. useContext Hook 5

IV. useDebugValue Hook 6

V. useDeferredValue Hook 7

VI. useEffect Hook 8

VII. useId Hook 9

VIII. useImperativeHandle Hook 10

IX. useRef Hook 11

X. useState Hook
How It Works 12

XI. useLayoutEffect Hook 13


Clients Feedback
XII. useMemo Hook 14

XIII. useTransition Hook 15

XIV. useSyncExternalStore Hook 16

XV. useReducer Hook 17

XVI. Custom Hook 18

By: Minal Sontakke


3

INTRODUCTION
In the fast-evolving world of web development,
React has become one of the most widely-used
libraries for building modern user interfaces.
Since its introduction, React has provided
developers with tools to create dynamic,
responsive applications, but one key innovation
has revolutionized how we write React
components: React Hooks.

Hooks were introduced in React to simplify


state management and side-effect handling
within functional components. They remove the
need for class components and offer a cleaner,
more modular way to manage complex logic.
With hooks, you can now handle state, context,
side effects, and more directly within your
functional components, leading to cleaner code
and improved performance.

By: Minal Sontakke


USECALLBACK
HOOK
CACHE THE RESULT

useCallback returns a memoised version of a function,


which is useful when passing functions as props to child
components to prevent unnecessary re-renders.

import React, { useState, useCallback } from 'react';

function Button({ onClick }) {


return <button onClick={onClick}>Click Me</button>;
}

function App() {
const [count, setCount] = useState(0);

const handleClick = useCallback(() => {


setCount(count + 1);
}, [count]); // Memoize the callback based on 'count'

return (
<div>
<p>Count: {count}</p>
<Button onClick={handleClick} />
</div>
);
}

useCallback memoizes handleClick so the function only


changes when the count value changes, preventing
unnecessary re-renders of the Button component.

4 By: Minal Sontakke


USECONTEXT
HOOK
READ AND SUBSCRIBE
CONTEXT
useContext allows you to access values from a context
without needing to pass props down manually at each
level of your component tree. This is useful for global
states like user data or theme settings.

import React, { createContext, useContext } from 'react';

const UserContext = createContext();

function UserInfo() {
const user = useContext(UserContext); // Access user from context
return <div>Welcome, {user.name}!</div>;
}

function App() {
const user = { name: 'Sam D' };

return (
<UserContext.Provider value={user}>
<UserInfo />
</UserContext.Provider>
);
}

createContext creates a new context.


useContext allows components to consume the
context value (user) without explicitly passing it as a
prop.

5 By: Minal Sontakke


USEDEBUGVALUE
HOOK
ADD LABEL TO CUSTOM HOOK

useDebugValue is used for debugging custom hooks. It


labels the output in React DevTools, making it easier to
see the state or value a hook is returning.

import { useState, useDebugValue } from 'react';

function useUserStatus(userId) {
const [isOnline, setIsOnline] = useState(false);

useDebugValue(isOnline ? 'Online' : 'Offline'); // Show custom label in DevTools

// Simulated status update logic here...

return isOnline;
}

function UserStatus({ userId }) {


const isOnline = useUserStatus(userId);

return <div>{isOnline ? 'User is online' : 'User is offline'}</div>;


}

useDebugValue: Displays custom labels in React DevTools


to help with debugging custom hooks.
Improves clarity when inspecting hook states during
development.

6 By: Minal Sontakke


USEDEFERREDVALUE
HOOK
DEFER UPDATING SOME OF THE UI

useDeferredValue lets you delay updates to a less


important state, improving UI responsiveness. It’s useful
when you want to show immediate feedback (like typing)
but defer expensive updates (like filtering data).

import { useState, useDeferredValue } from 'react';

function SearchApp() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query); // Delays updating the
search query

const results = performSearch(deferredQuery); // Simulated slow search

return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ul>{results.map(r => <li key={r}>{r}</li>)}</ul>
</div>
);
}

useDeferredValue: Delays the state update to prioritize


immediate UI feedback.
Keeps UI responsive during expensive operations like
filtering or rendering large lists.

7 By: Minal Sontakke


USEEFFECT
HOOK
SYNCHRONIZE
EXTERNAL SYSTEMS
The useEffect hook allows you to perform side effects
(e.g., fetching data, manipulating the DOM, or setting up
subscriptions) in functional components. It runs after the
render and can also clean up when the component
unmounts.

import React, { useEffect, useState } from 'react';

function Timer() {
const [time, setTime] = useState(0);

useEffect(() => {
const interval = setInterval(() => setTime(time => time + 1), 1000);

return () => clearInterval(interval); // Cleanup when the component


unmounts
}, []); // Empty dependency array makes this effect run once on mount

return <div>Timer: {time}s</div>;


}

The effect sets up a timer (setInterval) when the


component is first rendered (because of the empty
dependency array []).
The cleanup function (clearInterval) stops the timer
when the component unmounts, preventing memory
leaks.

8 By: Minal Sontakke


USEID
HOOK
GENERATE UNIQUE IDS FOR ACCESSIBILITY

useId generates a unique ID for accessible components,


useful for assigning unique keys to form elements or
components in lists.

import { useId } from 'react';

function Form() {
const id = useId(); // Generates a unique ID

return (
<div>
<label htmlFor={id}>Username</label>
<input id={id} type="text" />
</div>
);
}

useId: Generates a unique and stable ID, useful for


accessibility and keys.

9 By: Minal Sontakke


USEIMPERATIVEHANDLE
HOOK
CUSTOMIZE THE HANDLE

useImperativeHandle customizes the instance value that


is exposed to parent components when using ref. It is
used to limit what functionality can be accessed by the
parent component.

import React, { useImperativeHandle, forwardRef, useRef }


from 'react';

const CustomInput = forwardRef((props, ref) => {


const inputRef = useRef();

useImperativeHandle(ref, () => ({
focusInput: () => inputRef.current.focus()
}));

return <input ref={inputRef} type="text" />;


});

function Parent() {
const inputRef = useRef();

return (
<div>
<CustomInput ref={inputRef} />
<button onClick={() =>
inputRef.current.focusInput()}>Focus Input</button>
</div>
);
}

useImperativeHandle customizes the ref to only expose


the focusInput function to the parent component, even
though more properties exist on inputRef.
10 By: Minal Sontakke
USEREF
HOOK
REFERENCE A VALUE

The useRef hook provides a way to directly interact with


DOM elements or store a value that persists across
renders but does not trigger a re-render when updated.
It’s often used for accessing DOM elements.

import React, { useRef } from 'react';

function TextInput() {
const inputRef = useRef(); // Create a ref

const focusInput = () => {


inputRef.current.focus(); // Access the DOM element
directly
};

return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus the Input</button>
</div>
);
}

useRef creates a reference to an input element.


inputRef.current accesses the actual DOM element,
and focus() is called to focus the input field when the
button is clicked.

11 By: Minal Sontakke


USESTATE
HOOK
ADD STATE VARIABLE

The useState hook allows you to add state to functional


components. It returns an array containing two elements:
the current state and a function to update it. This hook is
used when you want to keep track of data that changes
over time, such as form inputs or a counter.

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // useState initializes 'count' to 0

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

useState(0) initializes the count variable to 0.


setCount updates the value of count when the button
is clicked, causing the component to re-render.

12 By: Minal Sontakke


USELAYOUTEFFECT
HOOK
FIRE BEFORE BROWSER

useLayoutEffect is similar to useEffect, but it runs


synchronously after all DOM mutations and before the
browser paints. It’s used when you need to measure the
DOM or make changes that should happen immediately
after render.

import React, { useLayoutEffect, useRef } from 'react';

function LayoutEffectExample() {
const divRef = useRef();

useLayoutEffect(() => {
console.log('LayoutEffect - Div size:',
divRef.current.offsetHeight);
});

return <div ref={divRef}>Hello, World!</div>;


}

useLayoutEffect runs after the DOM has been rendered


but before the browser paints, allowing you to read and
change layout properties like offsetHeight.

13 By: Minal Sontakke


USEMEMO
HOOK
CACHE THE RESULT

useMemo is used to memorise expensive calculations,


returning a cached result unless the dependencies
change. This improves performance by avoiding
unnecessary recalculations.

import React, { useState, useMemo } from 'react';

function ExpensiveCalculation({ number }) {


const result = useMemo(() => {
console.log('Calculating...');
return number * 2; // Imagine this is a heavy calculation
}, [number]);

return <div>Result: {result}</div>;


}

function App() {
const [num, setNum] = useState(1);

return (
<div>
<ExpensiveCalculation number={num} />
<button onClick={() => setNum(num + 1)}>Increment
Number</button>
</div>
);
}

useMemo caches the result of the calculation (number * 2).


The calculation is only re-run when number changes,
optimizing performance.

14 By: Minal Sontakke


USETRANSITION
HOOK
UPDATE STATE WITHOUT
BLOCKING
useTransition lets you make state updates feel smoother
by marking them as low-priority. This way, more urgent
updates (like user input) happen first, while the less
urgent ones (like filtering large data) are deferred.

import { useState, useTransition } from 'react';

function SearchApp() {
const [searchTerm, setSearchTerm] = useState('');
const [results, setResults] = useState([]);
const [isPending, startTransition] = useTransition();

const handleSearch = (e) => {


setSearchTerm(e.target.value);
startTransition(() => {
const filtered = performSearch(e.target.value); //
Simulated search
setResults(filtered);
});
};

return (
<div>
<input value={searchTerm} onChange={handleSearch} />
{isPending ? <p>Loading...</p> : <ul>{results.map(r =>
<li key={r}>{r}</li>)}</ul>}
</div>
);
}

startTransition: Defers less important state updates.


isPending: Shows pending state (e.g., "Loading...") during
15 the transition.
By: Minal Sontakke
USESYNCEXTERNALSTORE
HOOK
SUBSCRIBE AN EXTERNAL
STORE
useSyncExternalStore is used to subscribe to external
stores, keeping your component synced with global or
external state changes.

import { useSyncExternalStore } from 'react';

// External store setup


const store = { value: 0, listeners: new Set(),
subscribe(listener) { this.listeners.add(listener); return () =>
this.listeners.delete(listener); }, setValue(v) { this.value = v;
this.listeners.forEach(l => l()); }, getValue() { return
this.value; } };

function useStoreValue() {
return useSyncExternalStore(store.subscribe,
store.getValue);
}

function Counter() {
const value = useStoreValue();
return (
<div>
<p>{value}</p>
<button onClick={() => store.setValue(value +
1)}>Increment</button>
</div>
);
}

Keeps component synced with the latest value from an


external store, making state changes consistent.

16 By: Minal Sontakke


USEREDUCER
HOOK
ADD A REDUCER

useReducer is useful when state logic is more complex,


involving multiple state variables or when the next state
depends on the previous one. It works like Redux, using a
reducer function to manage the state.

import { useReducer } from 'react';

function reducer(state, action) {


switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<div>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'increment'
})}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement'
})}>Decrement</button>
</div>
);
}

useReducer: Manages complex state with a reducer


function and dispatch method.
dispatch: Sends actions to update state based on logic in
the reducer.
17 By: Minal Sontakke
CUSTOM
HOOK
SHARE FUNCTIONALITY

A custom hook is a function that uses one or more built-


in hooks to encapsulate reusable logic. Custom hooks
allow you to share functionality between components.

import { useState, useEffect } from 'react';

function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);

useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);

return () => window.removeEventListener('resize',


handleResize);
}, []);

return width;
}

function WindowWidthDisplay() {
const width = useWindowWidth();

return <div>Window width: {width}px</div>;


}

useWindowWidth is a custom hook that tracks the


window width using useState and useEffect.
This custom hook can now be reused in multiple
components without duplicating the logic.

18 By: Minal Sontakke


THANK YOU

CONNECT
MINAL
SONTAKKE
ON LINKEDIN

+123-456-7890

[email protected]

www.reallygreatsite.com

123 Anywhere St., Any City,


ST 12345

You might also like