0% found this document useful (0 votes)
21 views9 pages

Most Commonly Used React Hooks

Uploaded by

Yash pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views9 pages

Most Commonly Used React Hooks

Uploaded by

Yash pandey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Most Commonly Used React Hooks

22 May 2023 15:43

• Certainly! Here are 20 commonly used React hooks along with brief
descriptions of each: with code examples (see at plus icon on left)

1. useState: Allows you to add state to functional components. Returns the


current state value and a function to update that value.
import React, { useState } from 'react';

const Counter = () => {


const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default Counter;

2. useEffect: Performs side effects in functional components. Runs after


every render.
import React, { useEffect, useState } from 'react';

const Timer = () => {


const [time, setTime] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setTime((prevTime) => prevTime + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <p>Time: {time} seconds</p>;
};
export default Timer;

3. useContext: Accesses a context value within a functional component.


Allows components to consume values from a context provider.
import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');


const ThemeDisplay = () => {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
};
export default ThemeDisplay;

4. useReducer: Manages complex state logic using a reducer function.


Returns the current state and a dispatch function to trigger state
updates.
import React, { useReducer } from 'react';
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {

Index of This Notebook Page 1


switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const handleIncrement = () => {
dispatch({ type: 'increment' });
};
const handleDecrement = () => {
dispatch({ type: 'decrement' });
};
return (
<div>
<p>Count: {state.count}</p>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
);
};
export default Counter;

5. useRef: Creates a mutable value that persists across renders. Can be


used to access DOM elements or store mutable values.
import React, { useRef } from 'react';
const InputField = () => {
const inputRef = useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleFocus}>Focus</button>
</div>
);
};
export default InputField;

6. useMemo: Memoizes a value and prevents unnecessary computations.


Accepts a function an array of dependencies.
import React, { useMemo, useState } from 'react';
const ExpensiveComponent = () => {
// Some expensive computation
const expensiveValue = useMemo(() => {
// Expensive computation
return calculateExpensiveValue();
}, []);
return <p>Expensive Value: {expensiveValue}</p>;
};
export default ExpensiveComponent;

7. useCallback: Memoizes a function and prevents unnecessary re-creation


of function instances. Useful for optimizing performance when passing
callbacks to child components.
import React, { useCallback, useState } from 'react';
const Button = () => {

Index of This Notebook Page 2


const Button = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount((prevCount) => prevCount + 1);
}, []);
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
};
export default Button;

8. useLayoutEffect: Similar to useEffect but runs synchronously after all


DOM mutations. Useful for performing DOM measurements or triggering
synchronous re-renders.
import React, { useLayoutEffect, useRef } from 'react';
const ScrollToTopButton = () => {
const buttonRef = useRef();
useLayoutEffect(() => {
const handleScroll = () => {
const isVisible = window.scrollY > 100;
buttonRef.current.style.display = isVisible ? 'block' : 'none';
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
};
return (
<button ref={buttonRef} onClick={scrollToTop}>
Scroll to Top
</button>
);
};
export default ScrollToTopButton;

9. useImperativeHandle: The useImperativeHandle hook is used to customize


the instance value that is exposed by a parent component when using the
ref attribute. It allows you to define functions or values that can be
accessed externally through the ref of the child component. Here's an
example:
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
const InputComponent = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
getValue: () => {
return inputRef.current.value;
}
}));
return <input ref={inputRef} type="text" />;
});
const ParentComponent = () => {
const inputRef = useRef();
const handleClick = () => {

Index of This Notebook Page 3


const handleClick = () => {
inputRef.current.focus();
};
const handleGetValue = () => {
const value = inputRef.current.getValue();
console.log('Input value:', value);
};
return (
<div>
<InputComponent ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
<button onClick={handleGetValue}>Get Input Value</button>
</div>
);
};
export default ParentComponent;

10. useDebugValue: Provides a custom label for custom hooks in React


DevTools.
import React, { useState, useEffect, useDebugValue } from 'react';
function useCustomHook() {
const [count, setCount] = useState(0);
useEffect(() => {
// Some side effect code
document.title = `Count: ${count}`;
// Update the debug value to display in React DevTools
useDebugValue(`Count: ${count}`);
}, [count]);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
return { count, increment };
}
function App() {
const { count, increment } = useCustomHook();
return (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
}
export default App;

11. useMutationEffect: Similar to useLayouteffect but deprecated in favor


of useLayoutEffect. However, in earlier versions of React, there was a
useMutationEffect hook which was similar to useLayoutEffect. It allowed
performing synchronous side effects after DOM mutations, similar to the
deprecated componentWillMount lifecycle method. But note that as of
React 18, the useMutationEffect hook has been removed, and it is
recommended to use useEffect or useLayoutEffect instead, depending on
your use case.
12. useTransition: Allows you to defer rendering of a component until after
a certain time period to improve perceived performance. The
useTransition hook is used for creating transitions in React concurrent
mode. It allows you to indicate that a part of the UI is in a
transitional state, such as when rendering a loading spinner or
animating a component. Here's an example of using the useTransition
hook:
import React, { useState, useTransition } from 'react';
function ExampleComponent() {

Index of This Notebook Page 4


function ExampleComponent() {
const [showContent, setShowContent] = useState(false);
const [startTransition, isPending] = useTransition();
const handleClick = () => {
startTransition(() => {
setShowContent(!showContent);
});
};
return (
<div>
<button onClick={handleClick}>
{isPending ? 'Loading...' : showContent ? 'Hide Content' : 'Show
Content'}
</button>
{showContent && <div>Content goes here</div>}
</div>
);
}
export default ExampleComponent;

13. ErrorBoundary: (It's an component not hook provided by React) Creates


an error boundary for catching and handling errors within a component.
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log or handle the error here
}
render() {
if (this.state.hasError) {
// Render fallback UI when an error occurs
return <div>Something went wrong.</div>;
}
return this.props.children;
}
}
function ExampleComponent() {
// Wrap your component inside the ErrorBoundary
return (
<ErrorBoundary>
{/* Your component code here */}
</ErrorBoundary>
);
}
export default ExampleComponent;

14. useRouteMatch: Matches the current URL against a provided path pattern.
The useRouteMatch hook is a hook provided by React Router library,
which allows you to access the matched route information in your
components. Here's an example of how you can use the useRouteMatch
hook:
import React from 'react';
import { BrowserRouter as Router, Route, Link, useRouteMatch } from
'react-router-dom';
function App() {
return (

Index of This Notebook Page 5


return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Topics() {
// Use the useRouteMatch hook to get the current route match
const match = useRouteMatch();
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/topic1`}>Topic 1</Link>
</li>
<li>
<Link to={`${match.url}/topic2`}>Topic 2</Link>
</li>
<li>
<Link to={`${match.url}/topic3`}>Topic 3</Link>
</li>
</ul>
<Route path={`${match.path}/:topicId`} component={Topic} />
<Route exact path={match.path}>
<h3>Please select a topic.</h3>
</Route>
</div>
);
}
function Topic({ match }) {
return <h3>Requested Topic ID: {match.params.topicId}</h3>;
}
export default App;

15. useLocation: Accesses the current URL location. The useLocation hook is
provided by the React Router library and allows you to access the
current location object in your components. Here's an example of how
you can use the useLocation hook:
import React from 'react';
import { BrowserRouter as Router, Route, Link, useLocation } from
'react-router-dom';

Index of This Notebook Page 6


'react-router-dom';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Contact() {
// Use the useLocation hook to get the current location object
const location = useLocation();
return (
<div>
<h2>Contact</h2>
<p>Current URL: {location.pathname}</p>
</div>
);
}
export default App;

16. useHistory: Provides access to the browser's history object to navigate


between pages. The useHistory hook is provided by the React Router
library and allows you to access the browser's history object in your
components. Here's an example of how you can use the useHistory hook:
import React from 'react';
import { BrowserRouter as Router, Route, Link, useHistory } from 'react-
router-dom';
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>

Index of This Notebook Page 7


</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Router>
);
}
function Home() {
const history = useHistory();
const goToAbout = () => {
history.push('/about');
};
return (
<div>
<h2>Home</h2>
<button onClick={goToAbout}>Go to About</button>
</div>
);
}
function About() {
return <h2>About</h2>;
}
function Contact() {
return <h2>Contact</h2>;
}
export default App;

17. useInView: Detects whether an element is in the viewport or not. The


useInView hook is a popular hook used in React to determine whether an
element is currently in the viewport or not. Here's an example of how
you can use the useInView hook:
import React from 'react';
import { useInView } from 'react-intersection-observer';
function MyComponent() {
const [ref, inView] = useInView({
threshold: 0.5, // Percentage of element visible to be considered in
view
triggerOnce: true, // Only trigger once when the element enters the
viewport
});
return (
<div ref={ref}>
<h2>{inView ? 'In View' : 'Not In View'}</h2>
{/* Other content */}
</div>
);
}
export default MyComponent;

18. useDraggable: Enables draggable behavior on elements. The useDraggable


hook is not a built-in hook in React. However, you can create a custom
hook to implement draggable behavior in your components. Here's an
example of how you can create a useDraggable hook:
import { useState, useRef, useEffect } from 'react';
function useDraggable() {
const [isDragging, setIsDragging] = useState(false);
const draggableRef = useRef(null);
const offsetXRef = useRef(0);
const offsetYRef = useRef(0);
useEffect(() => {
const handleMouseDown = (event) => {

Index of This Notebook Page 8


const handleMouseDown = (event) => {
const { clientX, clientY } = event;
const rect = draggableRef.current.getBoundingClientRect();
offsetXRef.current = clientX - rect.left;
offsetYRef.current = clientY - rect.top;
setIsDragging(true);
};
const handleMouseMove = (event) => {
if (isDragging) {
const { clientX, clientY } = event;
draggableRef.current.style.left = `${clientX -
offsetXRef.current}px`;
draggableRef.current.style.top = `${clientY -
offsetYRef.current}px`;
}
};
const handleMouseUp = () => {
setIsDragging(false);
};
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
return () => {
document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
}, [isDragging]);
return {
draggableRef,
};
}
export default useDraggable;

To use the useDraggable hook in your component, you can do the


following:

import React from 'react';


import useDraggable from './useDraggable';
function MyComponent() {
const { draggableRef } = useDraggable();
return (
<div ref={draggableRef} style={{ position: 'absolute', top: 0, left:
0 }}>
Drag me!
</div>
);
}
export default MyComponent;

Index of This Notebook Page 9

You might also like