Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'use-debounce' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
function useWnResize(ref = false, delay = 500) {
const [windowSize, setWindowSize] = useState(null)
const getSize = useCallback(() => {
// Setting state to the updated matches
setWindowSize({
width: ref === false ? window.innerWidth : ref.current.offsetWidth,
height: ref === false ? window.innerHeight : ref.current.offsetHeight,
})
}, [ref])
const [resizeHandler] = useDebouncedCallback(() => {
getSize()
}, delay)
useEffect(() => {
if (!isSSR) {
// Add listener
window.addEventListener("resize", resizeHandler)
getSize()
}
return () => {
// Remove listener
!isSSR && window.removeEventListener("resize", resizeHandler)
}
}, [resizeHandler, ref, getSize])
export default function useSearchResults(fetch, { initialResults = null, debounceTimeout = 200 } = {}) {
const [result, setResult] = useState(initialResults);
const [isLoading, setIsLoading] = useState(false);
const currentSearchTerm = useRef(null);
const isDestroyed = useRef(false);
const [doSearch] = useDebouncedCallback(searchTerm => {
setIsLoading(true);
currentSearchTerm.current = searchTerm;
fetch(searchTerm)
.catch(() => null)
.then(data => {
if (searchTerm === currentSearchTerm.current && !isDestroyed.current) {
setResult(data);
setIsLoading(false);
}
});
}, debounceTimeout);
useEffect(
() =>
// ignore all requests after component destruction
() => {
function useMQResize(queries) {
const [queryMatch, setQueryMatch] = useState(null)
const keys = useRef(Object.keys(queries))
const handleQuery = useCallback(() => {
const updatedMatches = keys.current.reduce((acum, media) => {
acum[media] = !!window.matchMedia(queries[media]).matches
return acum
}, {})
// Setting state to the updated matches
setQueryMatch(updatedMatches)
}, [queries])
const [resizeHandler] = useDebouncedCallback(
() => {
handleQuery()
},
// Delay
500
)
useEffect(() => {
if (!isSSR && window.matchMedia) {
// Add listener
window.addEventListener("resize", resizeHandler)
handleQuery()
}
return () => {
// Remove listener
const ControlsEquation = (props) => {
const { editorChangeObject, onPendingChanges, onClose } = props;
const { changeNode, selectedNode, updateNode } = editorChangeObject;
const {
commitChanges,
revertChanges,
hasPendingChanges,
updateAttrs,
pendingAttrs,
} = useCommitAttrs(selectedNode.attrs, updateNode, onPendingChanges);
const { value, html } = pendingAttrs;
const [debouncedValue] = useDebounce(value, 250);
const hasMountedRef = useRef(false);
const isBlock = selectedNode.type.name === 'block_equation';
useEffect(() => {
// Avoid an initial call to the server's LaTeX renderer on mount
// We shouldn't need this anyway -- but moreover, it will sometimes produce HTML that is
// insubstantially different from that given in our Prosemirror schema definitions, making
// it appear as though there is a user-driven change to the node that needs to be committed
// or reverted.
if (!hasMountedRef.current) {
hasMountedRef.current = true;
return;
}
renderLatexString(debouncedValue, false, (nextHtml) => {
updateAttrs({ html: nextHtml });
});
useEffect( () => {
if (
calculatePriceRangeQueryState !== currentQueryPrices &&
currentQueryPrices !== undefined
) {
setCalculatePriceRangeQueryState( currentQueryPrices );
}
}, [
currentQueryPrices,
setCalculatePriceRangeQueryState,
calculatePriceRangeQueryState,
] );
// Defer the select query so all collection-data query vars can be gathered.
const [ shouldSelect, setShouldSelect ] = useState( false );
const [ debouncedShouldSelect ] = useDebounce( shouldSelect, 200 );
if ( ! shouldSelect ) {
setShouldSelect( true );
}
const collectionDataQueryVars = useMemo( () => {
return buildCollectionDataQuery( collectionDataQueryState );
}, [ collectionDataQueryState ] );
return useCollection( {
namespace: '/wc/store',
resourceName: 'products/collection-data',
query: {
...queryState,
page: undefined,
per_page: undefined,
const DomainPicker: FunctionComponent< Props > = ( {
defaultQuery,
onDomainSelect,
queryParameters,
} ) => {
const label = NO__( 'Search for a domain' );
const [ domainSearch, setDomainSearch ] = useState( '' );
const [ search ] = useDebounce( domainSearch.trim() || defaultQuery || '', selectorDebounce );
const suggestions = useSelect(
select => {
if ( search ) {
return select( DOMAIN_SUGGESTIONS_STORE ).getDomainSuggestions( search, {
include_wordpressdotcom: true,
include_dotblogsubdomain: true,
quantity: 4,
...queryParameters,
} );
}
},
[ search, queryParameters ]
);
const handleHasDomain = () => {
// eslint-disable-next-line no-console
const ControlsLink = (props) => {
const {
editorChangeObject: { activeLink },
onClose,
} = props;
const [href, setHref] = useState(activeLink.attrs.href);
const [debouncedHref] = useDebounce(href, 250);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => activeLink.updateAttrs({ href: debouncedHref }), [debouncedHref]);
const handleKeyPress = (evt) => {
if (evt.key === 'Enter') {
activeLink.updateAttrs({ href: href });
onClose();
}
};
return (
<div>
</div>
useEffect( () => {
if (
calculatePriceRangeQueryState !== currentQueryPrices &&
currentQueryPrices !== undefined
) {
setCalculatePriceRangeQueryState( currentQueryPrices );
}
}, [
currentQueryPrices,
setCalculatePriceRangeQueryState,
calculatePriceRangeQueryState,
] );
// Defer the select query so all collection-data query vars can be gathered.
const [ shouldSelect, setShouldSelect ] = useState( false );
const [ debouncedShouldSelect ] = useDebounce( shouldSelect, 200 );
if ( ! shouldSelect ) {
setShouldSelect( true );
}
const collectionDataQueryVars = useMemo( () => {
return buildCollectionDataQuery( collectionDataQueryState );
}, [ collectionDataQueryState ] );
return useCollection( {
namespace: '/wc/store',
resourceName: 'products/collection-data',
query: {
...queryState,
page: undefined,
per_page: undefined,
setCurrentOrganizationId,
organizationsAvailableToUser: organizations,
} = useCurrentOrganization();
const [searchResults, setResults] = useState(organizations);
const selectOrganization = (id) => () => {
setCurrentOrganizationId(id);
toggle();
};
// TODO: clean this up once
// https://github.com/orbitjs/orbit/pull/525
// is merged, where we'll be able to retrieve the query result
// without local filtering. (so we can skip the cache query step)
const performSearch = useDebouncedCallback(
async () => {
const filters = [{ attribute: 'name', value: `like:${searchTerm}` }];
if (!isSuperAdmin) {
filters.push({ attribute: 'scope-to-current-user', value: 'isnull:' });
}
await dataStore.query((q) => q.findRecords(ORGANIZATION).filter(filters), defaultOptions());
const records = await dataStore.cache.query((q) => q.findRecords(ORGANIZATION));
// TODO: MAY need to do a local filter on organizations that the current user owns
const filtered = records.filter((record) => {
const { name } = attributesFor(record);
if (!name) {
return false;
}
export default function AutoSavingInput({ value, onChange, InputElement, timeout }: IProps) {
const Input = InputElement || Form.TextArea;
const [localValue, setLocalValue] = useState(value);
const save = useDebouncedCallback((newValue) => onChange(newValue), timeout, []);
const onInputChange = (e: React.KeyboardEvent) => {
const newValue = e.currentTarget.value;
if (localValue === newValue) {
return;
}
setLocalValue(newValue);
save(newValue);
};
const onFormSubmit = (e: React.FormEvent) => {
e.preventDefault();
onChange(localValue);