List of all hooks in reactjs
React provides a variety of hooks that enable functional components to use state, lifecycle methods, and other React features without writing class components. Here is a list of all the built-in hooks in React:
Basic Hooks
-
useState: Allows you to add state to functional components.
const [state, setState] = useState(initialState);
-
useEffect: Lets you perform side effects in functional components (e.g., data fetching, subscriptions).
useEffect(() => { // side effect code }, [dependencies]);
-
useContext: Allows you to subscribe to React context without introducing nested components.
const value = useContext(MyContext);
Additional Hooks
-
useReducer: An alternative to
useState
for managing more complex state logic.const [state, dispatch] = useReducer(reducer, initialState);
-
useCallback: Returns a memoized callback function.
const memoizedCallback = useCallback(() => { // callback code }, [dependencies]);
-
useMemo: Returns a memoized value.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
-
useRef: Returns a mutable ref object whose
.current
property is initialized to the passed argument.const refContainer = useRef(initialValue);
-
useImperativeHandle: Customizes the instance value that is exposed when using
ref
in parent components.useImperativeHandle(ref, () => ({ // exposed methods }), [dependencies]);
-
useLayoutEffect: Similar to
useEffect
, but fires synchronously after all DOM mutations.useLayoutEffect(() => { // layout effect code }, [dependencies]);
-
useDebugValue: Can be used to display a label for custom hooks in React DevTools.
useDebugValue(value);
Custom Hooks
React also allows you to create your own custom hooks. A custom hook is a function whose name starts with use
and that can call other hooks.
Example of a Custom Hook
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
}
fetchData();
}, [url]);
return { data, loading };
}