React - Hooks
React - Hooks
Topics : React JS
Written on January 03, 2024
React Hooks are functions that allow you to use state and other React features in functional
O
components. They were introduced in React version 16.8 to provide a more convenient way to work
with state and side effects in functional components, eliminating the need for class components in
N
many cases.
H
1. useState:
useState allows you to add state to functional components. It returns an array with two elements:
C
the current state value and a function to update the state.
TE
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
YA
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
AR
);
}
2. useEffect:
useEffect is used for side effects in functional components. It can replace lifecycle methods in
class components.
function Example() {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch data or perform side effects here
// This function will run after every render
fetchData();
}, []); // The empty dependency array means this effect runs once after the initial render
return (
<div>
{/* Render UI based on the data */}
</div>
);
}
3. useContext:
O
function Example() {
const contextValue = useContext(MyContext);
N
return (
<div>
H
{/* Use the context value */}
</div>
);
}
C
4. useReducer:
TE
useReducer is a hook for managing more complex state logic. It is often preferable to useState
when the next state depends on the previous one.
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
function Example() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
</div>
);
}
5. useCallback and useMemo:
useCallback and useMemo are used to optimize performance by memoizing functions and values.
function Example() {
const [count, setCount] = useState(0);
const doubledValue = useMemo(() => count * 2, [count]); // Recalculated only if count changes
O
return (
<div>
N
<p>Count: {count}</p>
<p>Doubled: {doubledValue}</p>
<button onClick={increment}>Increment</button>
H
</div>
);
}
C
© Copyright Aryatechno. All Rights Reserved. Written tutorials and materials by Aryatechno
TE
YA
AR