React Hooks were introduced in version 16.8 of React, providing a powerful way to use state and other React features without writing a class. Hooks are functions that let you "hook into" React state and lifecycle features from function components. This chapter will cover the theory behind React Hooks and provide a comprehensive list of the most commonly used hooks.
Hooks offer a way to reuse stateful logic between components, making code more readable and maintainable. Before hooks, functional components were stateless, and only class components could hold state and manage lifecycle methods. Hooks unify the way we can use these features across all components.
const [count, setCount] = useState(0);
useEffect(() => { /* side effect logic */ }, [dependencies]);
const value = useContext(MyContext);
const [state, dispatch] = useReducer(reducer, initialState);
const memoizedCallback = useCallback(() => { /* callback logic */ }, [dependencies]);d
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const refContainer = useRef(initialValue);
ref
.useImperativeHandle(ref, () => ({ customInstance }));
useEffect
, but it fires synchronously after all DOM mutations.useLayoutEffect(() => { /* layout side effect logic */ }, [dependencies]);
useDebugValue(value);
const [isPending, startTransition] = useTransition();
const deferredValue = useDeferredValue(value);
const id = useId();
const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
In addition to the built-in hooks, React allows you to create your own custom hooks. Custom hooks start with the use
prefix and can call other hooks. This helps in abstracting and reusing logic.
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
Note : We will further discuss Hooks one by one in more detail.
React Hooks have revolutionized the way we write React applications by making stateful logic reusable, improving code readability, and removing the need for classes. Understanding and effectively using hooks is essential for modern React development.Happy coding !❤️