
- Name
- Sumit Kumar
Mastering React Hooks
React Hooks were introduced in React 16.8 and completely changed how we write React components. They allow you to use state and other React features without writing a class.
The Essentials
useState
The most basic hook for managing state in functional components.
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>
);
}
useEffect
Handles side effects like data fetching, subscriptions, or manually changing the DOM.
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`https://api.example.com/users/${userId}`)
.then(response => response.json())
.then(data => setUser(data));
// Optional cleanup function
return () => {
console.log('Component unmounted or userId changed');
};
}, [userId]); // Dependency array: only re-run if userId changes
if (!user) return <div>Loading...</div>;
return <div>{user.name}</div>;
}
Creating Custom Hooks
Custom hooks let you extract component logic into reusable functions. They must start with use.
Example: A hook to fetch data.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
fetchData();
}, [url]);
return { data, loading };
}
// Usage
function App() {
const { data, loading } = useFetch('https://api.example.com/data');
if (loading) return 'Loading...';
return <div>{JSON.stringify(data)}</div>;
}
Rules of Hooks
- Only Call Hooks at the Top Level: Don't call Hooks inside loops, conditions, or nested functions.
- Only Call Hooks from React Function Components: Don't call Hooks from regular JavaScript functions.
Conclusion
Hooks simplify state management and side effects in React, making your code cleaner and easier to understand. Mastering them is essential for any modern React developer.
Comments
Please sign in to leave a comment.