React Hooks are a set of functions that allow you to add state and other features to your functional components. Here is a list of some of the most commonly used React Hooks:
useState: Allows you to add stateful behavior to your functional components.
useEffect: Allows you to add side effects to your functional components, such as fetching data from an API or updating the document title.
useContext: Allows you to pass data down to child components without having to pass props through all the intermediate components.
useRef: Allows you to create a mutable reference that persists across renders.
useCallback: Allows you to memoize a function so that it only gets re-created when its dependencies change.
useMemo: Allows you to memoize a value so that it only gets re-computed when its dependencies change.
useReducer: Allows you to manage state using a reducer function, similar to how state is managed in Redux.
useLayoutEffect: Allows you to perform side effects immediately after the browser has painted the screen, before the user sees the updated content.
useDebugValue: Allows you to display custom debugging information in React DevTools.
These hooks allow you to add powerful functionality to your React components with minimal effort, making it easier to write clean, modular code.
useState is a function in React that allows you to add stateful behavior to your functional components. The function returns an array with two elements:
The current state value.
A function to update the state value.
The first element of the array is the current state value, which is initialized with the initial value that you pass as an argument to useState. You can access the current state value just like any other variable within your component.
The second element of the array is the state update function. When you call this function, it will update the state value with the new value that you pass as an argument. React will then re-render the component with the updated state value.
Here's an example of how to use useState to manage a simple counter:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
In this example, useState is used to initialize the count variable to 0. When the handleClick function is called, it updates the count variable by calling the setCount function with the new value. Finally, the component is re-rendered with the updated count value.
useEffect is a hook in React that allows you to add side effects to your functional components. Side effects are actions that happen outside of the normal flow of your component, such as fetching data from an API, manipulating the DOM, or setting up event listeners.
The useEffect function takes two arguments:
A function that contains the side effect logic.
An optional array of dependencies that the side effect depends on.
When you call useEffect, React will run the side effect function after the component has rendered. If you provide a list of dependencies, React will only re-run the side effect when one of the dependencies has changed.
Here's an example of how to use useEffect to fetch data from an API:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const json = await response.json();
setData(json);
}
fetchData();
}, []);
if (!data) {
return <p>Loading...</p>;
}
return (
<div>
<p>Data: {data}</p>
</div>
);
}
In this example, useEffect is used to fetch data from an API when the component is first rendered. The fetchData function is called within useEffect, and the resulting data is stored in state using the setData function. The empty array [] passed as the second argument ensures that useEffect only runs once when the component mounts.
As a best practice, you should always clean up any side effects that you create using useEffect. You can do this by returning a cleanup function from the side effect function. The cleanup function will be called when the component unmounts or when the dependencies change.
Here's an example of how to use useEffect with a cleanup function to set up and tear down a timer:
import React, { useState, useEffect } from 'react';
function Timer() {
const [time, setTime] = useState(0);
useEffect(() => {
const timerId = setInterval(() => {
setTime(time + 1);
}, 1000);
return () => {
clearInterval(timerId);
};
}, [time]);
return (
<div>
<p>Time: {time} seconds</p>
</div>
);
}
In this example, useEffect is used to set up a timer that updates the time state variable every second. The setInterval function returns an ID that is used to clear the timer in the cleanup function. The cleanup function is called when the component unmounts or when the time dependency changes.
useEffect is a powerful tool for managing side effects in your React components. By using this hook, you can keep your component code clean and concise, while still achieving the desired behavior. Just remember to follow best practices and clean up your side effects to avoid memory leaks and other issues.