React Hooks
React Hooks are special functions that allow you to use React features like state and lifecycle methods within functional components, without needing to convert them into class components. Introduced in React 16.8, they simplify code and make it easier to manage logic and side effects.
Some popular hooks:
Hooks make React components more reusable and concise!
React Hooks work by allowing functional components to have features like state and lifecycle methods, which were previously only available in class components. Each hook is essentially a JavaScript function that "hooks" into specific parts of React's internal logic (state, effects, etc.).
Key Principles of Hooks:
How Common Hooks Work:
Accesses values stored in React's Context API, avoiding the need to pass props down through multiple components.
Provides a way to reference DOM elements or persist values between renders without triggering re-renders.
An alternative to useState for managing more complex state logic, similar to how Redux reducers work.
How it works under the hood:
This mechanism allows functional components to handle dynamic behavior and lifecycle events as seamlessly as class components!
Custom Hooks:
Custom hooks are functions in React that allow you to reuse logic across multiple components. They encapsulate stateful logic (using built-in hooks like useState, useEffect, etc.) into a function that can be shared between components, making the code cleaner and more reusable.
Why Use Custom Hooks?
How to Create a Custom Hook
A custom hook is simply a function whose name starts with "use". Inside it, you can use React's built-in hooks to manage state, side effects, etc., and return the necessary values or functions for other components to use.
Example: Custom Hook for Fetching Data
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
export default useFetch;
Copy code
import { useState, useEffect } from 'react'; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch(url); const result = await response.json(); setData(result); } catch (error) { setError(error); } finally { setLoading(false); } }; fetchData(); }, [url]); return { data, loading, error }; } export default useFetch;
Using the Custom Hook in a Component
function MyComponent() {
const { data, loading, error } = useFetch('https://api.example.com/data');
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
Copy code
function MyComponent() { const { data, loading, error } = useFetch('https://api.example.com/data'); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <h1>Data:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }
Key Points:
Custom hooks make your React code more modular, clean, and reusable!