custom-hooks

typescript
import { useCallback, useEffect, useState } from "react";

interface Options {
  rootMargin?: string;
  threshold?: number;
}

IntersectionObserver infinite scroll hook

react hooks intersection-observer
by codesnips 3 tabs
javascript
import { useCallback, useEffect, useRef, useState } from 'react';

export function usePaginatedFetch(fetchPage, { pageSize = 20 } = {}) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

Infinite Scroll in React with IntersectionObserver and a Paginated Fetch Hook

react hooks infinite-scroll
by codesnips 3 tabs
typescript
import { useMemo } from "react";

export type SortDir = "asc" | "desc";
export interface SortConfig<T> {
  key: keyof T;
  dir: SortDir;

Memoized Async Search With a Cached Selector Hook in React

react hooks usememo
by codesnips 3 tabs
typescript
export interface Todo {
  id: string;
  title: string;
  done: boolean;
  pending: boolean;
}

Optimistic To-Do Toggle in React with Rollback via useReducer

react optimistic-ui hooks
by codesnips 3 tabs
typescript
export interface CartItem {
  sku: string;
  name: string;
  unitPrice: number; // cents
  qty: number;
}

Shopping Cart Pricing with a useReducer State Machine and a Pure Discount Engine

react usereducer typescript
by codesnips 3 tabs
javascript
export const required = (msg = 'This field is required') => (value) =>
  value && value.trim() !== '' ? '' : msg;

export const minLength = (n, msg) => (value) =>
  value && value.length >= n ? '' : msg || `Must be at least ${n} characters`;

Field-by-Field Signup Validation with a Reusable useForm Hook in React

react hooks forms
by codesnips 4 tabs
javascript
import { useState, useRef, useEffect, useCallback } from 'react';

export function useOnScreen(options = {}) {
  const [node, setNode] = useState(null);
  const [isIntersecting, setIsIntersecting] = useState(false);

Infinite Scroll in React with an IntersectionObserver useOnScreen Hook

react hooks intersection-observer
by codesnips 3 tabs
typescript
import { useEffect, useState } from "react";

export function useDebouncedValue<T>(value: T, delay = 300): T {
  const [debounced, setDebounced] = useState<T>(value);

  useEffect(() => {

Build a Debounced Search Box in React with a Reusable useDebouncedValue Hook

react hooks typescript
by codesnips 3 tabs