React Hooks

Certainly! React Hooks were introduced in React 16.8 as a way to add state and other React features to functional components without needing to write a class. Before the introduction of Hooks, state and lifecycle methods were only available in class components. With Hooks, functional components gained the ability to manage state and perform side effects, making them more powerful and flexible. Here are some key aspects of React Hooks: 




 1. useState: This Hook allows functional components to manage state. It returns a stateful value and a function to update it, similar to this.setState() in class components. Here's a basic 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>
);
}

2. useEffect: This Hook adds the ability to perform side effects in functional components, such as fetching data, subscribing to events, or manually changing the DOM. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. Here's an example:


import React, { useState, useEffect } from 'react';

function DataFetcher() {
const [data, setData] = useState(null);

useEffect(() => {
// Fetch data when component mounts
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));

// Cleanup function (optional)
return () => {
// Perform cleanup, e.g., unsubscribe from events
};
}, []); // Empty dependency array means this effect runs only once

return (
<div>
{data ? (
<p>Data: {data}</p>
) : (
<p>Loading...</p>
)}
</div>
);
}


3. Custom Hooks: Developers can create custom Hooks to encapsulate logic that is reused across multiple components. Custom Hooks are functions whose names start with "use" and may call other Hooks internally. They allow for better code organization and reuse. Here's a simple example of a custom Hook:


import { useState } from 'react';

function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);

const increment = () => {
setCount(count + 1);
};

const decrement = () => {
setCount(count - 1);
};

return { count, increment, decrement };
}

0 Comments