Server-Side Hooks and Custom Hooks in React
In this final blog, we’ll cover server-side hooks, such as useId, useDeferredValue, and useSyncExternalStore, and also discuss custom hooks.
1. useId
What is it? useId is used to generate unique IDs for elements, especially for accessibility purposes, like labeling form inputs.
Real-Life Example: Automatically generating unique IDs for form fields.
import React, { useId } from 'react';
function Form() {
const id = useId();
return (
<form>
<label htmlFor={id}>Enter your name</label>
<input id={id} type="text" />
</form>
);
}
2. useDeferredValue
What is it? useDeferredValue allows you to defer updates to a value until later, which can improve performance for non-urgent state updates.
Real-Life Example: You can use this to delay the rendering of certain UI components for smoother transitions.
import React, { useState, useDeferredValue } from 'react';
function Search() {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} />
<p>Search term: {deferredQuery}</p>
</div>
);
}
3. useSyncExternalStore
What is it? useSyncExternalStore is used for subscribing to external stores, ensuring the component’s state stays synchronized with external data.
Real-Life Example: You could use it for subscribing to a global state management system like Redux.
import React, { useSyncExternalStore } from 'react';
const store = {
getState: () => 'Hello, world!',
subscribe: (callback) => { setTimeout(callback, 1000); }
};
function App() {
const state = useSyncExternalStore(store.subscribe, store.getState);
return (
<div>
<p>External store value: {state}</p>
</div>
);
}
Custom Hooks
What is it? Custom hooks let you reuse logic between components. You can combine built-in hooks to create reusable patterns like useFetch or useAuth.
Real-Life Example: Creating a useFetch hook to handle data fetching in multiple components.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData);
}, [url]);
return data;
}
function App() {
const data = useFetch('https://api.example.com/data');
return (
<div>
{data ? JSON.stringify(data) : 'Loading...'}
</div>
);
}
With all these hooks, you now have the power to handle almost any use case in React!
Comments
Post a Comment