typescript
import { RefObject, useEffect, useRef } from "react";

type Handler = (event: MouseEvent | TouchEvent) => void;

export function useClickOutside<T extends HTMLElement>(
  ref: RefObject<T>,

Reusable useClickOutside Hook for Closing Dropdowns in React

react hooks typescript
by codesnips 3 tabs
php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostResource;

Cursor Pagination for Eloquent Queries Exposed as a JSON API in Laravel

laravel eloquent pagination
by codesnips 3 tabs
rust
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Page<T> {
    pub items: Vec<T>,
    #[serde(default)]

Streaming a Paginated HTTP API as a Rust Iterator

rust iterator pagination
by codesnips 3 tabs
php
<?php

namespace App\Report;

use App\Repository\OrderRepository;
use Symfony\Contracts\Cache\ItemInterface;

Cache an Expensive Sales Report in Symfony With a Stamped Key and Invalidation Subscriber

symfony caching psr-6
by codesnips 3 tabs
javascript
const MAX_LIMIT = 100;
const DEFAULT_LIMIT = 20;
const ALLOWED_ORDER = new Set(['asc', 'desc']);

function decodeCursor(raw) {
  const json = Buffer.from(raw, 'base64').toString('utf8');

Cursor-Based Pagination in Express With Query-Parsing Middleware

express pagination cursor-pagination
by codesnips 3 tabs
rust
use std::time::Duration;
use tokio_util::sync::CancellationToken;

pub struct Worker {
    id: usize,
    token: CancellationToken,

Graceful Task Shutdown in Tokio Using CancellationToken

tokio async cancellation
by codesnips 3 tabs
java
@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "orderExecutor")
    public ThreadPoolTaskExecutor orderExecutor() {

Debouncing Order Recalculations with Spring @Async and a Configured ThreadPoolTaskExecutor

spring-boot async thread-pool
by codesnips 3 tabs
java
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService orderService;

Testing a Spring Boot Controller Slice with @WebMvcTest, MockMvc and a Mocked Service

spring-boot testing mockmvc
by codesnips 3 tabs
rust
use pulldown_cmark::{html, Options, Parser};
use std::collections::HashSet;

pub struct SafeHtml(String);

impl SafeHtml {

Rendering Untrusted Markdown to Sanitized HTML with pulldown-cmark and ammonia

rust markdown html-sanitization
by codesnips 3 tabs
ruby
class CounterBuffer
  DELTA_HASH = "counter:deltas".freeze

  READ_RESET = <<~LUA.freeze
    local v = redis.call('HGET', KEYS[1], ARGV[1])
    if v then redis.call('HDEL', KEYS[1], ARGV[1]) end

Debounce Expensive Counter Cache Updates with a Throttled Redis Buffer in Rails

rails redis counter-cache
by codesnips 3 tabs
rust
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub user_id: u64,

Signing and Verifying Session Cookies with HMAC-SHA256 in Rust

hmac sessions cookies
by codesnips 3 tabs
javascript
import { useEffect, useRef } from 'react';

const TABBABLE = [
  'a[href]',
  'button:not([disabled])',
  'textarea:not([disabled])',

Accessible React Modal with Portal, Focus Trap, and Escape-to-Close Hook

react accessibility modal
by codesnips 3 tabs