React hooks
Created By: chatGPT
React Hooks are functions that let you use state and other React features without writing a class. Introduced in React 16.8, Hooks allow you to manage component state and lifecycle events in a more functional style. Here are a few of the common hooks used in React:
useState is a Hook that lets you add state to functional components. Here’s a simple 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>
);
}
useEffect allows you to perform side effects in your function components. It can be used for data fetching, subscriptions, or manually changing the DOM. Here's how you can use it:
import React, { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array ensures this runs only once
return data.map(item => <div key={item.id}>{item.name}</div>);
}
Custom Hooks are a way to extract reusable logic into a function. This is useful when you have logic that needs to be shared across multiple components. Here's a simple example of a custom hook:
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setIsLoading(false);
});
}, [url]);
return { data, isLoading };
}
To use the Custom Hook, it can be done in a component like this:
React Hooks provide a powerful way to manage state and lifecycle events in a cleaner and more concise manner. Embracing Hooks can lead to more readable and maintainable code.import React from 'react';
import useFetch from './useFetch';
function App() {
const { data, isLoading } = useFetch('https://api.example.com/data');
if (isLoading) return <div>Loading...</div>;
return (
<div>
{data && data.map(item => <div key={item.id}>{item.name}</div>)}
</div>
);
}