In React, a Hook is a special function that lets you “hook into” React features like state and lifecycle methods without writing a class component.
React introduced Hooks in version 16.8 to make it easier to share logic between components and simplify the code structure using functional components.
Why Hooks?
Before Hooks, if you wanted to use features like state or side effects, you had to use class components. But class components often become hard to manage, especially when logic is split across lifecycle methods like componentDidMount
and componentDidUpdate
.
Hooks solve this by allowing you to use these features inside functional components, making code cleaner, reusable, and easier to understand.
Commonly Used React Hooks
React provides several built-in hooks. Here are the most important ones:
1. useState()
- Lets you add state to a functional component.
- Syntax: jsxCopyEdit
const [count, setCount] = useState(0);
count
is the current state, andsetCount
is a function to update it.
Example:
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>
);
}
2. useEffect()
- Performs side effects in components (like fetching data, setting up subscriptions, etc.).
- Replaces lifecycle methods like
componentDidMount
,componentDidUpdate
, andcomponentWillUnmount
.
Example:
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // Only run when `count` changes
return <button onClick={() => setCount(count + 1)}>Click</button>;
}
3. useContext()
- Lets you use values from a React context without manually using
<Context.Consumer>
. - Useful for themes, authentication, and global state.
4. useRef()
- Used to persist values across renders or directly access DOM elements.
- Doesn’t cause re-render on update.
5. useMemo()
and useCallback()
- Used for performance optimization.
useMemo
memoizes a computed value.useCallback
memoizes a function.
Custom Hooks
You can also create your own hooks to reuse logic across components. Custom hooks are just functions that start with the word use
and can call other hooks.
Example:
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return [count, increment];
}
Rules of Hooks
To use hooks correctly, follow these two rules:
- Only call hooks at the top level (not inside loops, conditions, or nested functions).
- Only call hooks from React functions (functional components or custom hooks).
Conclusion
Hooks are a powerful feature in React that allow developers to write cleaner and more reusable code using functional components. Whether you’re managing state, working with side effects, or creating reusable logic, hooks make React development simpler and more elegant.