Additional Built-in Hooks in React
Last Updated :
05 Apr, 2024
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:
The useReducer hook
useReducer Hook provides an alternative to useState for managing complex state logic. It's often used when state transitions depend on the previous state or when the next state depends on the previous state.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState);
- Here, 'initialState' is the initial state of the component.
- 'state' is the current state value.
- 'dispatch' is a function used to dispatch an action to update the state.
Example: Below is an example of useReducer hook.
JavaScript
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Gfgarticle() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<br></br>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement
</button>
</>
)
};
export default Gfgarticle;
Output:

The useRef hook
useRef hook helps to return 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.
Syntax:
const refContainer = useRef(initialValue);
- 'initialValue' is optional and is used for the reference. It can be anything, including null.
Example: Below is an example of useRef hook.
JavaScript
import React, {
useState,
useEffect,
useRef
} from 'react';
function Gfgarticle() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);
useEffect(() => {
count.current = count.current + 1;
});
return (
<>
<input type="text" value={inputValue}
onChange={(e) => setInputValue(e.target.value)} />
<h1>
The page has been rendered {count.current} times
</h1>
</>
);
}
export default Gfgarticle;
Output:
The useCallback Hook
useCallback hook helps to return a memoized callback that only changes if one of the dependencies has changed. This can help optimize performance by preventing unnecessary re-renders of child components.
Syntax:
const memoizedCallback = useCallback(
() => {
// Function logic
},
[dependencies]
);
- Here 'dependencies' are an optional array of dependencies. The memoized callback will only be recalculated if one of these dependencies changes.
Example: Below is an example of useCallback hook.
JavaScript
import React, {
useState,
useCallback
} from 'react';
function Gfgarticle() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((prevCount) => prevCount + 1);
}, []);
return (
<>
<p>Count: {count}</p>
<button onClick={increment}>
Incement
</button>
</>
)
}
export default Gfgarticle;
Output:

The useMemo Hook
useMemo Hook returns a memoized value. It will only recompute the memoized value when one of the dependencies has changed. It is basically used to do expensive calculation only when the dependencies change.
Syntax:
const memoizedValue = useMemo(() => {
// Computation
return expensive Computation value;
}, [dependencies]);
Example: Below is an example of useMemo hook.
JavaScript
import React, {
useState,
useMemo
} from 'react';
function Gfgarticle({ count }) {
const [count, setCount] = useState(0);
const [number, setNumber] = useState(0);
const expensiveCalculation = (num) => {
for (let i = 0; i < 100000000; i++) {
num += i;
}
return num;
};
const increment = () => {
setCount(count + 1);
if (count % 10 === 0) {
setNumber(count + 1);
}
}
const calculation = useMemo(
() => expensiveCalculation(number), [number]);
return (
<>
<h1>This is a Memo Hook</h1>
<div>Count: {count}</div>
<button onClick={increment}>
Increase
</button>
<h2>Expensive Calculation</h2>
{calculation}
</>
)
}
export default Gfgarticle;
Output:

The useLayoutEffect Hook
useLayoutEffect Hook is similar to useEffect. But it fires synchronously after all DOM mutations. This can be useful for measuring DOM nodes or performing layout calculations. It is best to find the dimensions.
Syntax:
useLayoutEffect(() => {
// Effect function
// Perform synchronous operations requiring DOM measurements or layout calculations
// Return a cleanup function (optional)
return () => {
// Cleanup logic
};
}, [dependencies]);
Example: Below is an example of useLayoutEffect hook.
JavaScript
import React, {
useLayoutEffect,
useState,
useRef
} from 'react';
function Gfgarticle() {
const [width, setWidth] = useState(0);
const ref = useRef();
useLayoutEffect(() => {
setWidth(ref.current.clientWidth);
}, []);
return (
<>
<h1>This is useLayoutEffect Hook</h1>
<p ref={ref}>Width: {width}px</p>
</>
)
};
export default Gfgarticle;
Output:

The useImperativeHandle Hook
It is a React hook that allows you to customize the instance value that is exposed when using 'ref' with 'React.forwardRef'. It's particularly useful when you're working with third-party libraries or integrating with imperative APIs and need more control over the exposed methods or properties of a component.
Syntax:
useImperativeHandle(ref, () => {
// Return an object representing the public API of the component
return {
exposedFunction1,
exposedFunction2,
};
}, [dependencies]);
Example: Below is an example of useImperativeHandle hook.
JavaScript
import React, {
useRef,
useImperativeHandle,
forwardRef
} from 'react';
// Child component that forwards a ref
const ChildComponent = forwardRef((props, ref) => {
const inputRef = useRef(null);
// Expose custom imperative methods
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
reset: () => {
inputRef.current.value = '';
}
}));
return <input ref={inputRef} />;
});
// Parent component using the child component
function Gfgarticle() {
const childRef = useRef(null);
const handleFocusClick = () => {
childRef.current.focus();
};
const handleResetClick = () => {
childRef.current.reset();
};
return (
<div>
<h1>This is useImperativeHandle Hook</h1>
<ChildComponent ref={childRef} /><br></br><br></br>
<button onClick={handleFocusClick}>
Focus Input
</button>
<button onClick={handleResetClick}>
Reset Input
</button>
</div>
);
}
export default Gfgarticle;
Output:

The useDebugValue Hook
useDebugValue Hook in React is used to display additional debug information for custom hooks in React DevTools. It's primarily used for development purposes to provide more insights into the state or behavior of custom hooks.
Syntax:
useDebugValue(value, formatter);
- Here, 'value' is the value to be displayed in the React DevTools.
- 'formatter' is a function that formats the value for display in the DevTools. It's useful for providing more informative labels or transforming the value into a more readable format.
Example: Below is an example of useDebugValue hook.
JavaScript
import React, {
useState,
useEffect,
useDebugValue
} from 'react';
function Gfgarticle() {
const [count, setCount] = useState(0);
// Displaying count value in React DevTools
useDebugValue(count > 0 ?
'Positive' : 'Non-positive');
useEffect(() => {
const timer = setInterval(() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <div>Count: {count}</div>;
};
export default Gfgarticle;
Output:

Conclusion
In conclusion, React's built-in hooks revolutionized the way developers write components by providing a powerful and intuitive way to manage state, effects, context, and more within functional components. Introduced in React version 16.8.0, hooks enable developers to leverage advanced React features without relying on class components, leading to cleaner, more concise code and improved code reuse.
Similar Reads
Built-in React Hooks
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 tailor
5 min read
Building Custom Hooks Library in React
Custom hooks in React allow developers to encapsulate and reuse logic, making it easier to manage state and side effects across multiple components. As applications become complex, developers often repeat similar patterns for state management, API calls, or event handling. This can lead to code dupl
4 min read
Context Hooks in React
Context Hooks are a feature in React that allows components to consume context values using hooks. Before Hooks, consuming context required wrapping components in Consumer or using a Higher Order Component (HOC). Context Hooks streamline this process by providing a more intuitive and concise way to
3 min read
New Hooks in React 18
React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state a
5 min read
Data Fetching Libraries and React Hooks
Data fetching libraries like React Query and React Hooks simplify how developers fetch and manage data in React applications. These tools provide easy-to-use functions like 'useQuery' and 'SWR' that streamline API interactions and state management, improving code readability and reducing boilerplate
6 min read
Effect Hooks in React
Effect Hooks 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 co
5 min read
How to create a Custom Hook in React ?
In web application development, developers often need to reuse logic multiple times, which can become difficult to manage manually. So, the custom hook can be used to solve the problem of reusing complex stateful logic across multiple components. What are Custom Hooks?Custom Hooks are special functi
4 min read
How to add code input in React JS?
In this article, we are going to learn how we can add Code Input in React JS. React is a front-end JavaScript library for constructing user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Approach to add code input: To incorporate our
2 min read
Other Hooks in React
React provides specialized built-in hooks for building reusable components and libraries. While they are used less, these hooks are important in providing library authors to create robust and user-friendly applications. Among these specialized hooks are useDebugValue and useId, that provides unique
3 min read
React.js useImperativeHandle Additional Hook
The useImperativeHandle hook in react is used to modify the instance of child component while using refs. It is an additional hook that works with refs and allows us to customize the instance values of Child Components without directly using DOM. Syntax:useImperativeHandle(ref, createHandle, [deps])
2 min read