Understanding React Hooks & Custom Hooks: A Beginner's Guide
Introduction
React Hooks are a new feature in React that allows you to use state and other React features without writing a class. They were introduced in React 16.8 and have been widely adopted as a way to write functional and reusable components.
React Hooks by exmaple
Here's an example of how you can use the useState
hook to add state to a functional component:
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
The useState
hook takes a single argument, which is the initial state, and returns an array with two elements: the current state and a function to update it. In the example above, we declare a new state variable called count
with an initial value of 0
, and a function called setCount
to update it.
There are many other React Hooks that you can use to perform different tasks, such as useEffect
, useContext
, and useReducer
. You can find out more about them in the React documentation.
Default React Hooks
Here is a list of all the React Hooks that are currently available in the latest version of React:
useState
: This hook allows you to add state to functional components. It takes a single argument, which is the initial state, and returns an array with two elements: the current state and a function to update it.useEffect
: This hook allows you to perform side effects in functional components. It takes a function as an argument, which will be called after the component has rendered. You can use it to perform tasks such as fetching data or setting up subscriptions.useContext
: This hook allows you to access the value of a context object in a functional component. It takes a context object as an argument and returns the current context value.useReducer
: This hook allows you to use a reducer function to manage state in a functional component. It takes a reducer function and an initial state as arguments, and returns the current state and a dispatch function.useCallback
: This hook returns a memoized callback function. It can be used to optimize the performance of components that rely on props or state changes.useMemo
: This hook returns a memoized value. It can be used to optimize the performance of expensive calculations in a component.useRef
: This hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.useImperativeHandle
: This hook allows you to customize the instance value that is exposed to parent components when using ref. It takes a ref and a createHandle function as arguments.useLayoutEffect
: This hook is similar touseEffect
, but it fires synchronously after all DOM mutations. It should be used sparingly, because it blocks the browser from updating the screen until the effect has finished.useDebugValue
: This hook can be used to display a label for a custom hook in the React DevTools profiler. It takes a value as an argument and displays it next to the hook's name in the Profiler.
Custom Hooks
Custom Hooks are a new feature in React that allows you to extract component logic into reusable functions. They are a way to share logic across components, and they make it easier to reuse code and write testable components.
Here's an example of a custom hook that extracts the logic for fetching data from a REST API:
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
setData(data);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
}
fetchData();
}, [url]);
return { data, loading, error };
}
To use this custom hook, you can import it into your component and call it inside the component's function body:
import { useFetch } from './useFetch';
function MyComponent() {
const { data, loading, error } = useFetch('https://api.example.com/endpoint');
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return <p>Data: {data}</p>;
}
Custom Hooks follow the same naming convention as regular React Hooks, starting with the word use
and using camelCase. They can call other Hooks and can be composed to build more complex logic.
tl;dr
React Hooks are a new feature in React that allow you to use state and other React features without writing a class. They are a way to share logic across components, and they make it easier to reuse code and write testable components. There are several built-in Hooks, such as useState
, useEffect
, and useContext
, that perform different tasks.
You can also create your own custom Hooks by extracting component logic into reusable functions. Custom Hooks follow the same naming convention as regular React Hooks, starting with the word use
and using camelCase. They can be called inside the function body of a component and can be composed to build more complex logic.