React Hooks were introduced in React 16.8 to allow functional components to use state and lifecycle features that were previously only available in class components. Hooks provide a more direct and concise way to manage state, side effects, and other React features within functional components.
Key Concept
State Hook (useState
):
useState
allows functional components to manage state. It returns an array with two elements: the current state value and a function that lets you update it.- Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Effect Hook (useEffect
):
useEffect
enables performing side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.- Example:
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
const [data, setData] = useState(null);
useEffect(() => {
// Perform side effect (e.g., data fetching) here
// Update state with the fetched data
}, []); // Dependency array to control when the effect runs
}
Context Hook (useContext
):
useContext
provides a way to consume values from a React context without nesting components.- Example:
import React, { useContext } from 'react';
const MyContext = React.createContext();
function MyComponent() {
const contextValue = useContext(MyContext);
// Access contextValue here
}
Reducer Hook(`useReducer`):
useReducer
is useful for managing more complex state logic. It takes a reducer function and the initial state as arguments.- Example:
import React, { useReducer } from 'react';
function reducer(state, action) {
// Handle different actions and return a new state
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, initialState);
// Access state and dispatch here
}
These are some of the essential React Hooks. They enable developers to write more readable and maintainable code by encapsulating stateful logic within functional components.