0% found this document useful (0 votes)
4 views10 pages

HOOKs IN REACT

The document provides an overview of various React hooks, including useState, useEffect, useContext, useRef, useReducer, useMemo, useCallback, useLayoutEffect, useImperativeHandle, and useId. Each hook is explained with its purpose and includes example code demonstrating its usage. The conclusion summarizes the primary function of each hook.

Uploaded by

Gaurav Dhakate
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)
4 views10 pages

HOOKs IN REACT

The document provides an overview of various React hooks, including useState, useEffect, useContext, useRef, useReducer, useMemo, useCallback, useLayoutEffect, useImperativeHandle, and useId. Each hook is explained with its purpose and includes example code demonstrating its usage. The conclusion summarizes the primary function of each hook.

Uploaded by

Gaurav Dhakate
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/ 10

HOOK IN REACT

1. useState Hook

What it does?
It lets you add state (data that changes) to your function component.

Example & Explanation:

import { useState } from "react"; // Import useState from React

function Counter() {
const [count, setCount] = useState(0);
// useState(0) initializes "count" with 0 and "setCount" is used
to update it.

return (
<div>
<p>Count: {count}</p> {/* Show the current count */}
<button onClick={() => setCount(count + 1)}>Increment</button>
{/* When clicked, increase count by 1 */}
</div>
);
}

export default Counter;


2. useEffect Hook

What it does?
It lets you run code when the component loads, updates, or unmounts. (Used
for API calls, timers, etc.)

Example & Explanation:

import { useState, useEffect } from "react"; // Import useState &


useEffect

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

useEffect(() => {
const interval = setInterval(() => setTime(time + 1), 1000);
// Every 1 second, increase time by 1
return () => clearInterval(interval); // Clean up timer when
component unmounts
}, [time]); // Runs every time "time" changes

return <p>Time: {time} sec</p>; // Show the time


}

export default Timer;


3. useContext Hook

What it does?
It lets you share data (like themes, user info) between components without
passing props.

Example & Explanation:

import { createContext, useContext } from "react"; // Import context


functions

const ThemeContext = createContext("light"); // Create a Theme


Context with default "light"

function ThemeComponent() {
const theme = useContext(ThemeContext); // Get theme value from
context
return <p>Current Theme: {theme}</p>; // Show current theme
}

export default function App() {


return (
<ThemeContext.Provider value="dark">
{/* Provide "dark" as the theme */}
<ThemeComponent /> {/* Child component can use it */}
</ThemeContext.Provider>
);
}
4. useRef Hook

What it does?
It stores a reference to an element or value without causing re-renders.

Example & Explanation:

import { useRef } from "react"; // Import useRef

function InputFocus() {
const inputRef = useRef(null); // Create a reference

const focusInput = () => {


inputRef.current.focus(); // Focus on the input field
};

return (
<div>
<input ref={inputRef} type="text" placeholder="Type
something..." />
<button onClick={focusInput}>Focus Input</button>
{/* Clicking this focuses input */}
</div>
);
}

export default InputFocus;


5. useReducer Hook

What it does?
It is like useState but better for managing complex state (like counters, forms).

Example & Explanation:

import { useReducer } from "react"; // Import useReducer

const reducer = (state, action) => {


// Reducer function (handles different actions)
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 });
// useReducer(reducer, initialState)

return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment"
})}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-
</button>
</div>
);
}

export default Counter;


6. useMemo Hook

What it does?
It optimizes performance by caching expensive calculations.

Example & Explanation:

import { useState, useMemo } from "react";

function ExpensiveCalculation({ num }) {


const squared = useMemo(() => {
console.log("Calculating square...");
return num * num;
}, [num]); // Only re-calculates when "num" changes

return <p>Squared Value: {squared}</p>;


}

function App() {
const [number, setNumber] = useState(2);

return (
<div>
<button onClick={() => setNumber(number +
1)}>Increase</button>
<ExpensiveCalculation num={number} />
</div>
);
}

export default App;


7. useCallback Hook

What it does?
It memoizes functions to prevent unnecessary re-creation.

Example & Explanation:

import { useState, useCallback } from "react";

function Button({ handleClick }) {


return <button onClick={handleClick}>Click me</button>;
}

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

const increment = useCallback(() => {


setCount((prev) => prev + 1);
}, []); // Memoizes function, so it doesn't re-create on re-render

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

export default App;


8. useLayoutEffect Hook

What it does?
Like useEffect, but runs before the screen updates.

Example & Explanation:

import { useState, useLayoutEffect } from "react";

function LayoutEffectExample() {
const [color, setColor] = useState("red");

useLayoutEffect(() => {
setColor("blue"); // Updates before painting the screen
}, []);

return <p style={{ color }}>This text is blue!</p>;


}

export default LayoutEffectExample;


9. useImperativeHandle Hook

What it does?
It customizes what a ref exposes.

Example & Explanation:

import { useRef, useImperativeHandle, forwardRef } from "react";

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


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

const inputRef = useRef(null);

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


});

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

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

export default Parent;


10. useId Hook

What it does?
It generates unique IDs for accessibility.

Example & Explanation:

import { useId } from "react";

function Form() {
const id = useId();

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

export default Form;

Conclusion
• useState → Manages state
• useEffect → Runs side effects
• useContext → Shares data
• useRef → References elements
• useReducer → Manages complex state
• useMemo → Optimizes calculations
• useCallback → Optimizes functions
• useLayoutEffect → Runs before paint
• useImperativeHandle → Controls ref exposure
• useId → Generates unique IDs

You might also like