Concept of hooks in React
What Are Hooks in React?
React Hooks are a way to use state and other React features in functional components, rather than having to use class components. They were introduced in React 16.8 and have since become a popular way to write React components.
There are several built-in hooks, such as useState and useEffect, that make it easy to add state and side effects to functional components.
The useState hook is used to add a state to a functional component. It takes an initial value as an argument and returns an array with two elements: the current state and a function to update the state. For example, the following code uses the useState hook to add a "count" state to a component:
import { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
The useEffect hook is used to add side effects, such as data fetching or subscriptions, to a functional component. It takes a function as an argument, which is called after the component is rendered. The function can return a cleanup function that is called before the component is unmounted. For example, the following code uses the useEffect hook to fetch data from an API:
import { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://my-api.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<>
{data ? <p>Data: {data}</p> : <p>Loading...</p>}
</>
);
}
In addition to the built-in hooks, you can also create your own custom hooks to share logic between components. Custom hooks are just functions that start with the word "use" and can call other hooks. For example, the following code creates a custom hook to handle a form input:
import { useState } from 'react';
function useFormInput(initialValue) {
const [value, setValue] = useState(initialValue);
function handleChange(event) {
setValue(event.target.value);
}
return {
value,
onChange: handleChange
};
}
function MyComponent() {
const name = useFormInput('');
return (
<>
<label>
Name:
<input type="text" {...name} />
</label>
</>
);
}
In conclusion, React Hooks are a powerful tool that makes it easy to add state and side effects to functional components. They allow you to write more readable, reusable, and maintainable code and also provide the ability to share logic between components using custom hooks.
And Keep Learning till the Next Time
Assalamualaikum - Allahuma Barik
Peace Out✌️