Skip to content

Instantly share code, notes, and snippets.

@bpas247
bpas247 / state-updates-are-async.md
Last active March 17, 2023 17:12
State Updates Are Asynchronous

State Updates Are Asynchronous

The gist of it

You do this.

const handleEvent = e => {
  setState(e.target.value);
  console.log(state);
}
@Shrugsy
Shrugsy / objEntries.ts
Last active January 30, 2021 06:33
Allows using `Object.entries` with Typescript while retaining key type information with. Example: https://tsplay.dev/aNnPdW. Note: see discussion here before using this, as keys are intentionally typed as only `string` by design: https://github.com/microsoft/TypeScript/pull/12253
export type Entries<T> = {
[K in keyof T]: [K, T[K]];
}[keyof T][];
/**
* Helper to use `Object.entries` while retaining key type information.
* Input object should be cast `as const` for maximum effectiveness.
*/
export function objEntries<T extends Record<string, unknown>>(obj: T): Entries<T> {
return Object.entries(obj) as Entries<T>;
@Shrugsy
Shrugsy / useStableCallback.ts
Last active November 24, 2022 18:13
React hook that accepts a given callback, and provides a new callback with a stable reference, which will itself always call the latest version of the provided callback. Useful for dealing with third party components that use stale closures. Example: https://tsplay.dev/Bmx07m
import { useRef, useCallback} from 'react';
/**
* Accepts a given callback, and provides a new callback with a stable reference,
* which will itself always call the latest version of the provided callback.
* Useful for dealing with third party components that use stale closures.
* @param callback - the original callback desired to be called
* @returns A new callback with a stable reference, which when called,
* calls the latest provided callback
* @deprecated - This implementation may have future issues in concurrent mode, as it mutates
@Shrugsy
Shrugsy / rtkQueryCacheUtils.ts
Last active July 9, 2024 14:11
RTK Query cache utils. Useful abstractions for creating `provides`/`invalidates` cache data tags against endpoints.
import { FetchBaseQueryError } from '@rtk-incubator/rtk-query/dist';
/**
* Default tags used by the cacher helpers
*/
const defaultTags = ["UNAUTHORIZED", "UNKNOWN_ERROR"] as const;
type DefaultTags = typeof defaultTags[number];
function concatErrorCache<T, ID>(
existingCache: CacheList<T, ID>,
@click2install
click2install / useResizeObserver.ts
Last active August 28, 2021 11:30
[useResizeObserver] - A React hook for observing any element resize.
import { RefObject, useEffect, useState } from "react";
import ResizeObserver from "resize-observer-polyfill";
type BoundingRect = Omit<DOMRectReadOnly, "toJSON">;
export function useResizeObserver<T extends HTMLElement>(target: RefObject<T>)
{
const [state, setState] = useState<BoundingRect>({ bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0, x: 0, y: 0 });