React Hooks_ The only guide you’ll ever need _ Hygraph
React Hooks_ The only guide you’ll ever need _ Hygraph
Easily restore your project to a previous version with our new Instant One-click Backup Recovery
Blog Developer tutorials React Hooks: The only guide you’ll ever need
Frontend React
https://hygraph.com/blog/react-hooks 1/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
In this post
The useSyncExternalStore
Conclusion
https://hygraph.com/blog/react-hooks 2/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
https://hygraph.com/blog/react-hooks 3/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
function Counter() {
const [count, setCount] = useState(0); // Initial state i
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me<
</div>
);
}
https://hygraph.com/blog/react-hooks 4/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
https://hygraph.com/blog/react-hooks 5/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
// Cleanup function
return () => {
document.title = 'Default Title';
};
}, [count]); // Dependency array
//Component return() here
}
https://hygraph.com/blog/react-hooks 6/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
'use client';
import { useState, useEffect } from 'react';
import { GraphQLClient } from 'graphql-request';
import Link from 'next/link';
const hygraph = new GraphQLClient(
'https://api-eu-central-1.hygraph.com/v2/ck8sn5tnf01gc01z
);
const QUERY = `
query ProductPageQuery($slug: String!) {
product(where: { slug: $slug }) {
name
description
price
}
}
https://hygraph.com/blog/react-hooks 7/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
`;
export default function Product({ params }) {
const [product, setProduct] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchProduct = async () => {
try {
const { product } = await hygraph.request(QUERY, {
setProduct(product);
} catch (error) {
console.error('Error fetching product:', error);
} finally {
setIsLoading(false);
}
};
fetchProduct();
}, [params.slug]); // Fetch only when slug changes
return (
<>
<Link href="/">Home</Link>
{isLoading ? (
<p>Loading...</p>
) : (
<>
<h1>{product.name}</h1>
<p>{product.description}</p>
<p>€{product.price / 100}</p>
</>
)}
</>
);
}
How it works:
reducer.
https://hygraph.com/blog/react-hooks 9/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
"use client"
import { useReducer, useEffect } from 'react';
import { GraphQLClient, gql } from 'graphql-request';
import Link from 'next/link';
const QUERY = `
{
products {
slug
name
id
}
}
`;
const initialState = {
products: [],
loading: true,
error: null
};
https://hygraph.com/blog/react-hooks 10/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
useEffect(() => {
const fetchProducts = async () => {
try {
const { products } = await hygraph.request(QUERY);
dispatch({ type: 'FETCH_SUCCESS', payload: products
} catch (error) {
dispatch({ type: 'FETCH_ERROR', payload: error.mess
}
};
fetchProducts();
}, []);
return (
<div>
<h1>Products</h1>
{state.loading ? (
<p>Loading...</p>
) : state.error ? (
<p>Error: {state.error}</p>
) : (
<ul>
{state.products.map(({ slug, name, id }) => (
<li key={id}>
<Link href={`/products/${slug}`}>{name}</Link
</li>
))}
</ul>
)}
https://hygraph.com/blog/react-hooks 11/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
</div>
);
}
https://hygraph.com/blog/react-hooks 12/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
return (
<div>
Count: {count}
<button onClick={incrementCounter}>Increment</button>
<button onClick={decrementCounter}>Decrement</button>
</div>
);
};
https://hygraph.com/blog/react-hooks 13/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
https://hygraph.com/blog/react-hooks 14/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
<h2>Factorial Calculator</h2>
<input
https://hygraph.com/blog/react-hooks 15/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
type="number"
value={number}
onChange={(e) => setNumber(parseInt(e.target.value)
/>
<ExpensiveCalculation number={number} />
</div>
);
}
export default Counter;
https://hygraph.com/blog/react-hooks 16/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
https://hygraph.com/blog/react-hooks 17/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
shared data.
Example
function TextInput() {
const inputRef = useRef(null);
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
https://hygraph.com/blog/react-hooks 19/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Now, let's discuss the useId Hook, a simple yet powerful tool
for enhancing accessibility in React applications.
The Hook used is a utility for generating unique IDs that are
stable across the server and the client renders. This is
particularly important for building accessible web
applications that rely on labels and relationships between
elements, as it ensures consistent IDs for associating
elements like labels and form inputs.
How it works:
https://hygraph.com/blog/react-hooks 20/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
function MyComponent() {
const inputId = useId(); // Generate a unique ID
const labelId = useId();
return (
<div>
<label htmlFor={inputId}>My Input:</label>
<input id={inputId} type="text" />
<p aria-describedby={labelId}>This is a description f
</div>
);
}
In this example, the useId Hook generates unique IDs for the
input and label elements, ensuring a correct association
https://hygraph.com/blog/react-hooks 21/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
How it works:
It takes two arguments: the value you want to defer (it can
be of any type) and an optional timeout in milliseconds.
React prioritizes rendering other parts of the UI that depend
on the non-deferred value. This means that if the non-
deferred value changes, React will immediately update those
parts, while the parts that rely on the deferred value will
update later in a less urgent manner.
Example
function MyComponent() {
const [text, setText] = useState('');
const deferredText = useDeferredValue(text);
return (
<div>
<input value={text} onChange={(e) => setText(e.target
<ExpensiveList items={deferredText} />
</div>
);
}
https://hygraph.com/blog/react-hooks 22/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Complex Calculations.
https://hygraph.com/blog/react-hooks 23/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
useDebugValue(count); // Display 'count' in DevTools
// ... (rest of your custom Hook logic)
}
https://hygraph.com/blog/react-hooks 24/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
},
}));
function ParentComponent() {
const childRef = useRef(null);
https://hygraph.com/blog/react-hooks 25/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Focus Child Input</butt
</div>
);
}
https://hygraph.com/blog/react-hooks 26/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
browser paints.
How it works:
Example
function MyComponent() {
const [dimensions, setDimensions] = useState({ width: 0,
const myRef = useRef(null);
useLayoutEffect(() => {
const element = myRef.current;
if (element) {
setDimensions({
width: element.offsetWidth,
height: element.offsetHeight
});
https://hygraph.com/blog/react-hooks 27/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
}
}, []); // Empty dependency array ensures it runs only on
return (
<div ref={myRef}>
This div's dimensions are: {dimensions.width} x {dime
</div>
);
}
Example
useInsertionEffect(() => {
// Code to inject styles or DOM nodes
const styleElement = document.createElement('style');
document.head.appendChild(styleElement);
return () => {
// Cleanup function (optional) to remove the injected n
document.head.removeChild(styleElement);
};
}, [dependencies]); // Optional dependency array
https://hygraph.com/blog/react-hooks 29/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
The useSyncExternalStore
function MyComponent() {
const storeState = useSyncExternalStore(
store.subscribe, // Subscribe to the store
store.getSnapshot, // Get the current snapshot
);
return <div>{storeState}</div>;
}
https://hygraph.com/blog/react-hooks 30/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
How it works
Example
https://hygraph.com/blog/react-hooks 31/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
function MyComponent() {
const [isPending, startTransition] = useTransition();
const [value, setValue] = useState('');
return (
<div>
<input type="text" value={value} onChange={handleChan
{isPending ? <div>Loading...</div> : <HeavyComponent
</div>
);
}
https://hygraph.com/blog/react-hooks 32/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
How it works:
https://hygraph.com/blog/react-hooks 33/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Example
function MyComponent() {
const [comments, setComments] = useState([]);
// ...
}
How it works:
Example
function MyComponent() {
const [commentState, addComment] = useActionState(
(text) => fetch('/api/comments', { method: 'POST', body
);
// ...
}
https://hygraph.com/blog/react-hooks 35/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Conclusion
BLOG AUTHOR
Chidi Eze
Technical writer
Chidi is a software engineer and technical
writer with experience in building user-friendly
applications and creating content around
composable architectures.
Your email
Submit
How to …
React React
GraphQL
useRef( useCallb
- A… - A…
React
Learn how Prevent
useEffec
to use unnecessa
React's…
- A… re-…
Master
React
useEffec…
https://hygraph.com/blog/react-hooks 37/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
Support Frameworks
Terms
Privacy
Imprint
Sitemap
PRODUCT RESOURCES
Features What Is A Headless CMS?
Pricing Events
Changelog Blog
https://hygraph.com/blog/react-hooks 38/39
14/01/2025, 17:28 React Hooks: The only guide you’ll ever need | Hygraph
https://hygraph.com/blog/react-hooks 39/39