React Snippets
Searchable, copy-paste-ready React code snippets.
6 results
import { useState, useEffect, useRef } from 'react';
interface UseIntersectionObserverOptions
extends Partial<IntersectionObserverInit> {
threshold?: number | number[];
rootMargin?: string;
}
Intersection Observer Hook for Lazy Loading and Animations
A lightweight, reusable React hook that triggers callbacks when elements enter or leave the viewport—ideal for lazy-loading images or starting animations.
import { useState, useEffect, useRef } from 'react';
export function FadeIn({ children }: { children: React.ReactNode }) {
const [isVisible, setIsVisible] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const node = ref.current;Fade-in animation with requestAnimationFrame
A performant, CSS-in-JS fade-in animation using useState, useEffect, and requestAnimationFrame for smooth entrance transitions.
import { useState, useCallback, useMemo } from 'react';
interface UseFormOptions<T> {
initialValues: T;
validate?: (values: T) => Partial<Record<keyof T, string>>;
}
interface UseFormReturn<T> {Lightweight useForm hook with validation and dirty tracking
A minimal, self-contained React hook for form state management with validation, dirty tracking, and submission handling—no external dependencies.
import { useState, useEffect, useRef } from 'react';
export function DebouncedSearchInput({
onSearch,
delay = 300,
}: {
onSearch: (query: string) => void;
delay?: number;Debounced search input with useEffect and useRef
A reusable search input that delays API calls until user stops typing for a specified duration.
import { useState, useCallback } from 'react';
function useToggle(initialValue: boolean = false) {
const [value, setValue] = useState<boolean>(initialValue);
const toggle = useCallback(() => {
setValue(prev => !prev);
}, []);Custom useToggle hook with optional initial state
A lightweight, reusable React hook for managing boolean toggle state with optional initial value.
import { useState, useEffect, useRef, useCallback } from 'react';
interface AccessibleModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: React.ReactNode;
}Accessible Modal with Focus Trapping and Dismissal
A fully accessible React modal that traps focus, supports ESC key and click-outside dismissal, and announces state changes to screen readers.