Open In App

Built-in React Hooks

Last Updated : 20 Feb, 2024
Like Article

In React, built-in Hooks are like tools that empower your components with various functionalities. They give you the flexibility to use different features without having to create class components. You can either utilize the hooks provided by React or mix and match them to create custom hooks tailored to your needs. Here’s a list of all the pre-built hooks available in React.

State Hooks

State in React allows a component to keep track of information such as user input or the current state of the component. For instance, imagine a form where you type in your name. State would remember what you typed. Similarly, in an image gallery, state would remember which image you selected to display. It’s like a memory bank for your component to hold onto important data.

When using state in a component add one of these state.

  • useState enables components to manage and update their own state without using classes.
  • useReducer is used to manage complex state logic through a reducer function.
const Counter () =>{
cosnt [count, steCount] = useState('0');

Context Hooks

Context in React acts as a global store for sharing data between components, allowing distant components to access this data without the need for prop drilling, thereby simplifying state management and making it more efficient.

  • useContext it is used to consume data from a Context in a functional component.
const Theme ()=>{
const themeDark = useContext(ThemeContext);

Refs Hooks

React refs store non-rendering data like DOM node references or timeout IDs, without triggering re-renders. They enable interaction with non-React systems, like browser APIs, aiding integration with external libraries and imperative logic. Serving as an “escape hatch” from React’s standard data flow, refs offer flexibility and enhance compatibility with diverse environments.

  • useRef is used to create mutable references that persist across renders in functional components.
  • useImperativeHandler customizes the instance value that is exposed when using ref with functional components.
const App () =>{
const myRef = useRef(null);
const handleClick = () => {

Effect Hooks:

Effects in React allow components to interact with and stay synchronized with external systems, such as handling network requests, manipulating the browser’s DOM, managing animations, integrating with widgets from other UI libraries, and working with non-React code. Essentially, effects help components communicate and coordinate with the world outside of React.

  • useEffect is used to connect component to an external system.
const ClassRoom ()=>{
useEffect(() => {
// Effect code here
return () => {
//Here clean up code };
}, [dependencies]);

There are two different useEffect approach that are rarely used.

  • useLayoutEffect performs a side effect immediately after the browser has painted the screen.
  • useInsertionEffect is used before ReactJS makes changes to the DOM, and in this libraries can insert the dynamic CSS.

Performance Hooks:

To make your React app run faster, a smart strategy is to avoid doing unnecessary tasks. For instance, you can instruct React to reuse previous calculations that are already saved, or to avoid redoing a render if the data hasn’t changed since the last time. This helps your app be more efficient and responsive.

Used this to skip calculation and unnecessary re-rendirng, one of these are.

  • useMemo is used to memoize the result of a function computation, preventing unnecessary recalculations.
  • useCallback used to memoize functions, preventing unnecessary re-renders in child components.
const TodoFucntion ()=>{
const seeTodos = useMemo(() =>
filterTodos(todos, tab), [todos, tab]);

  • useTransition is used to manage transitions of UI elements, improving user experience during asynchronous updates.
  • useDeferredValue is used to delay the update of a value until certain conditions are met, enhancing performance by deferring non-critical updates.

Resource Hooks:

Components in React can access resources without storing them as part of their state. For instance, a component can retrieve a message from a Promise or obtain styling information from a context without needing to manage that data internally. This approach simplifies component logic and promotes more efficient resource utilization.

If you read a value from a resource the use this hook.

  • use is used when you read a value from resource like from Promises or context.
const  ChatComponent({ chatPromise }) => {
const chat = use(chatPromise);
const themeDark = use(ThemeContext);
// ...

Other Hooks

Example : Below is an example of built-in React Hooks.


import React, { useState }
    from 'react';
import ThemeContext
    from './ThemeContext';
import AnotherComponent
    from './UseCounter';
import './App.css';
const App = () => {
    const [theme, setTheme] = useState('white');
    return (
        <ThemeContext.Provider value={theme}>
            <div className={`theme-container
            ${theme === 'white' ?
                    'white-theme' : 'black-theme'}`}>
                <button onClick={() =>
                    setTheme(theme === 'white'
                        ? 'black' : 'white')}>
                    Toggle Theme
                <UseCounter />
export default App;


import React, { createContext } from 'react';
const ThemeContext = createContext();
export default ThemeContext;


import React, {
    from 'react';
// Context for managing theme
const ThemeContext = React.createContext();
// Reducer function for managing counter state
const counterReducer = (state, action) => {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 };
        case 'decrement':
            return { count: state.count - 1 };
            throw new Error();
const UseCounter = () => {
    // useState to manage counter state
    const [state, dispatch] =
        useReducer(counterReducer, { count: 0 });
    // useEffect to log whenever counter changes
    useEffect(() => {
        console.log('Counter value changed:',
    }, [state.count]);
    // useContext to get theme
    const theme = useContext(ThemeContext);
    // useRef to access and focus on the input element
    const inputRef = useRef(null);
    // useCallback to memoize the increment function
    const increment = useCallback(() => {
        dispatch({ type: 'increment' });
    }, [dispatch]);
    return (
        <div style={{ color: theme }}>
            Counter: {state.count}
            <button onClick={increment}>
            <button onClick={() =>
                dispatch({ type: 'decrement' })}>
            <input ref={inputRef} type="text" />
export default UseCounter;




Similar Reads

When is it best to use custom hooks instead of built-in React hooks?
Custom hooks in React are useful when you want to extract and reuse stateful logic across multiple components. While built-in React hooks like useState, useEffect, and useContext cover many common scenarios, there are cases where creating custom hooks can enhance code organization, readability, and reusability. When to Choose for Custom Hooks in Re
2 min read
Additional Built-in Hooks in React
Hooks are functions that allow you to "hook" into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes. We will discuss the various Additional Built-in Hooks: Table of Content The u
6 min read
Explain the new feature of React hooks introduced in React v16.8
React v16.8 is no less than a miracle for all the React developers because this version of React introduced hooks to all of us. Before its release, the developer community was tired of using class components but they still had to use them because the functional component does not provide many features that the class component provides. But after ho
7 min read
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components. Table of Cont
4 min read
What are React Hooks, and why were they added to React?
React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components, making them more powerful and flexible. Hooks Addr
2 min read
What are the React Router hooks in React v5?
React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information about the desired URL and navigating through web pages
5 min read
How to set an object key inside a state object in React Hooks?
We can update a React hooks state object that has a nested object containing objects with index keys with the following approach, Before doing so, consider the following example: Example: Following is the default state object: const [data, setData] = useState({ name:'', contact:'', address:{ 0:{}, 1:{}, } }) Following is the desired output after up
2 min read
How to use componentWillMount() in React Hooks?
The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a ho
2 min read
React Suite Notification Props & Hooks
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Notification Component allows the user to display a notification message globally. The notification is also used with a toaster in react-based applications. &lt;Notification&gt; Props: closable: It is a boolean
4 min read
Things You Should Know About React Hooks
React...We all know the importance of this library in the tech industry. Most of the applications are switching to React because of its advantages and features. There are many features of React. React hooks is one of them. React hooks was first released in October 2018. In React a lot of developers use the lifecycle method which is nothing, but jus
4 min read