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 = () => {
myRef.current.focus();
};
}
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.
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.
JavaScript
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
</button>
<UseCounter />
</div>
</ThemeContext.Provider>
);
};
export default App;
JavaScript
import React, { createContext } from 'react';
const ThemeContext = createContext();
export default ThemeContext;
JavaScript
import React, {
useEffect,
useContext,
useReducer,
useRef,
useCallback
}
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 };
default:
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);
}, [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' });
inputRef.current.focus();
}, [dispatch]);
return (
<div style={{ color: theme }}>
Counter: {state.count}
<button onClick={increment}>
Increment
</button>
<button onClick={() =>
dispatch({ type: 'decrement' })}>
Decrement
</button>
<input ref={inputRef} type="text" />
</div>
);
};
export default UseCounter;
Output:
Output
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects