5 Types of React Hooks
React Hooks are a way to use state and other React features in functional components. They were introduced in React 16.8 and have since become a fundamental part of the React ecosystem. In this article, we’ll take a look at all the available React Hooks and how to use them in your projects.
useState
The most basic Hook, useState
allows you to add state to your functional components. It returns an array with two values: the current state, and a function to update it. Here's an example of how to use it:
import { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
useEffect
useEffect
allows you to synchronize a component with an external system. It takes two arguments: a callback function, and an array of dependencies. The callback function will be called after the component has rendered, and any time one of the dependencies changes. Here's an example of how to use it to fetch data from an API:
import { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://my-api.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<>
{data ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</>
);
}
useContext
useContext
allows you to consume values from a context without having to pass them down through props. It takes one argument, the context object, and returns the current value. Here's an example of how to use it to consume a theme context:
import { useContext } from 'react';
const ThemeContext = React.createContext('light');
function Example() {
const theme = useContext(ThemeContext);
return (
<>
<p>The theme is {theme}</p>
</>
);
}
useReducer
useReducer
is a Hook that allows you to manage state in a more complex way than useState
. It takes two arguments: a reducer function, and an initial state. It returns the current state, and a dispatch function to update it. Here's an example of how to use it to manage a to-do list:
import { useReducer } from 'react';
function todoReducer(state, action) {
switch (action.type) {
case 'add':
return {
todos: [...state.todos, action.payload]
};
case 'remove':
return {
todos: state.todos.filter(todo => todo.id !== action.payload)
};
default:
return state;
}
}
function Example() {
const [state, dispatch] = useReducer(todoReducer, { todos: [] });
return (
<>
<ul>
{state.todos.map(todo => (
<li key={todo.id}>
{todo.text}
<button onClick={() => dispatch({ type: 'remove', payload: todo.id })}>
Remove
</button>
</li>
))}
</ul>
<input
type="text"
placeholder="Add a todo"
onKeyPress={event => {
if (event.key === 'Enter') {
const id = Date.now();
const text = event.target.value;
dispatch({ type: 'add', payload: { id, text } });
event.target.value = '';
}
}}
/>
</>
);
}
In this example, we have defined a todoReducer function that takes in the state and an action. The function has a switch statement that checks the action type and performs the corresponding operation on the state. We then use the useReducer Hook in our component and pass in the reducer function and an initial state. The Hook returns an array that contains the current state and the dispatch function, which we use to update the state by dispatching the corresponding action.
useCallback
useCallback
is a Hook that allows you to memoize a function, so it only changes if one of its dependencies changes. This can be useful in situations where you have a component that re-renders frequently, and you don't want to recreate a callback function on every render. Here is an example of how to use the useCallback
Hook:
import { useCallback } from 'react';
function Example({ value }) {
const memoizedCallback = useCallback(() => {
console.log(value);
}, [value]);
return <button onClick={memoizedCallback}>Click me</button>;
}
In this example, we have a component that receives a value prop and a button. When the button is clicked, it will log the current value to the console. We use the useCallback
Hook to memoize the callback function that will be passed to the onClick prop of the button. We pass in the callback function as the first argument, and an array of dependencies as the second argument. In this case, the callback function depends on the value prop, so it will only change if the value prop changes.
Note that useCallback is used to prevent unnecessary re-renders of functional components that are children of the component that is using useCallback.