Hooks are functions introduced in React 16.8 that allow you to use state and lifecycle features in functional components without using class components.
Common React Hooks
1. useState
Manages local state in functional components.
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
2. useEffect
Performs side effects like fetching data, updating the DOM, or subscribing to events.
import React, { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <h2>Seconds: {seconds}</h2>;
}
3. useRef
Access DOM elements directly or store mutable variables.
import React, { useRef } from "react";
function InputFocus() {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
Why Hooks Are Useful
- Avoid class components
- Reuse stateful logic with custom hooks
- Simplify code and improve readability
- Handle side effects cleanly
Conclusion
Hooks revolutionized React development by enabling state and lifecycle management in functional components, making code cleaner and reusable.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP