Why Hooks?
Before Hooks, state and lifecycle methods were only available in class components, which made code harder to read and reuse.
Hooks allow us to:
- Use state in functional components
- Handle lifecycle behavior (mount, update, unmount)
- Write cleaner and reusable code
- Avoid complex class syntax
Hooks were introduced to simplify React code and improve logic reuse.
useState Hook
The useState hook is used to add state to a functional component.
Syntax
const [count, setCount] = useState(0);
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
useEffect Hook
useEffect is a React Hook used to perform side effects in functional components.
What are Side Effects?
Side effects are operations that interact with the outside world, such as:
- Fetching data from an API
- Updating the DOM
- Setting up timers or intervals
- Subscribing to events
Syntax
useEffect(() => {
// side effect code
});