React Hooks are a set of functions provided by React to manage state and side effects in functional components. They were introduced in React 16.8 to allow functional components to have side effects, local component state, context features, refs, and more, which were previously possible only in class components. The two most basic hooks are `useState` and `useEffect`, but there are several others, each serving a unique purpose.
Here are some of the basic React Hooks:
`useState` is a Hook that allows you to add state to your functional components. It returns an array with two elements: the current state value and a function that lets you update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
`useEffect` lets you perform side effects in your function components. It's like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` combined in class components.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
return () => {
document.title = 'React App';
};
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
`useContext` lets you subscribe to React context without introducing nesting, providing a more straightforward way to access context values.
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <div>Current theme is {theme}</div>;
}
`useReducer` is usually preferable to `useState` when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
import React, { useReducer } from 'react';
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</div>
);
}
`useCallback` will return a memoized version of the callback that only changes if one of the dependencies has changed. It’s useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
import React, { useState, useCallback } from 'react';
function App() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
return <button onClick={increment}>Increment {count}</button>;
}
`useMemo` is a Hook that will only recompute the memoized value when one of the dependencies has changed. It’s useful for expensive calculations.
import React, { useMemo, useState } from 'react';
function App() {
const [count, setCount] = useState(1);
const factorial = useMemo(() => {
let result = 1;
for (let i = 2; i <= count; i++) result *= i;
return result;
}, [count]);
const handleChange = (event) => {
setCount(Number(event.target.value));
};
return (
<div>
<input type="number" value={count} onChange={handleChange} />
<p>Factorial of {count} is {factorial}</p>
</div>
);
}
`useRef` can create mutable objects which hold a `.current` property. It does not cause re-render when the object is changed.
import React, { useRef, useEffect } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
useEffect(() => {
inputEl.current.focus();
}, []);
return <input ref={inputEl} />;
}
`useImperativeHandle` customizes the instance value that is exposed when using `React.forwardRef`.
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
function App() {
const inputRef = useRef();
return (
<div>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</div>
);
}
`useLayoutEffect` has the same signature as `useEffect`, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render.
`useDebugValue` can be used to display a label for custom hooks in React DevTools.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here