Introduction to Hooks in React
1. What are Hooks?
Hooks are special functions introduced in React version 16.8 that allow developers to use state and other React features without writing class components. Hooks enable functional components to manage local state, handle side effects, and more, providing the flexibility of class components with a simpler and more readable syntax.
2. Why Were Hooks Introduced?
Before hooks, functional components were limited. They could receive props and render UI, but they lacked the ability to manage state or handle lifecycle methods. To implement these features, developers had to use class components, which often led to more complex code. Hooks were introduced to:
this
binding and lifecycle method confusion.
3. Basic Rules of Hooks
4. Commonly Used Hooks
React provides several built-in hooks to manage various aspects of component behavior. Here are the most commonly used hooks:
1. useState
The useState
hook allows you to add state to functional components. It returns a pair: the current state value and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count is the state variable, setCount is the state updater function.
return (
Current count: {count}
);
}
useState(0)
initializes the count
state variable with a value of 0.
The setCount
function is used to update the count
value.
2. useEffect
The useEffect
hook is used to handle side effects in functional components, such as fetching data, subscribing to events, or updating the DOM. It runs after the component renders and can be configured to run on specific state changes.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup function to prevent memory leaks.
}, []); // Empty dependency array ensures this effect runs only once, after the initial render.
return Elapsed time: {seconds} seconds
;
}
useEffect
sets up a timer that increments the seconds
state every second.
The cleanup function inside useEffect
clears the timer when the component unmounts.
3. useContext
The useContext
hook allows you to access context values in functional components without using the Context.Consumer
component. This is useful for sharing data like user information, theme, or authentication status across the component tree.
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
);
}