Skip to content

Instantly share code, notes, and snippets.

View async-update.js
import { useState } from "react";
import { wait } from "./wait";
export function FunctionalUpdates() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter(counter + 1);
}
View functional-update.js
import { useState } from "react";
import { wait } from "./wait";
export function FunctionalUpdates() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter(counter + 1);
}
View functional-updates-wait.js
export function wait({ miliseconds }) {
return new Promise((resolve) => setTimeout(resolve, miliseconds));
}
View use-callback.js
import { useCallback, useState } from "react";
import { wait } from "./src/FunctionalUpdates/wait";
export function FunctionalUpdates() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter(counter + 1);
}
View simple-update.js
import { useState } from "react";
export function FunctionalUpdates() {
const [counter, setCounter] = useState(0);
function handleIncrement() {
setCounter(counter + 1);
}
return (
View batch-photos-list.js
export function PhotosList() {
const onUpdate = useCallback(() => {
return new Promise((resolve) =>
setTimeout(resolve, getRandomBetween(1500, 2000))
);
}, []);
const { photos, updatePhotos } = usePhotos({
photos: DEFAULT_PHOTOS,
onUpdate,
View batch-other-utilities.js
export function usePhotos({}) {
// ...
const removePhotosLockedFlag = useCallback(
(_pendingUpdates) =>
setPhotos((_photos) =>
_photos.map((photo) => {
const updatedItem = _pendingUpdates[photo.id];
if (updatedItem) {
return Object.assign({}, photo, {
View batch-is-update-needed-and-get-reset-update-items.js
export function isUpdateNeeded(original, itemUpdate) {
const fieldsToOmit = [LOCKED_FLAG_KEY];
const keysToCompare = Object.keys(itemUpdate).filter(
(key) => ![...fieldsToOmit, "id"].includes(key)
);
return !isEqual(
pick(original, keysToCompare),
pick(itemUpdate, keysToCompare)
);
View batch-perform-update.js
const performUpdates = useDebouncedCallback(
async () => {
if (!hasPendingUpdates(pendingUpdates)) {
return;
}
clearPendingUpdates();
applyUpdatesToPhotos(pendingUpdates);
try {
View batch-update-photos.js
const updatePhotos = useCallback(
(itemsUpdates) => {
const { toReset, toUpdate } = getItemsToResetAndUpdate(
itemsUpdates,
photos
);
setPendingUpdates(
update(pendingUpdates, {
$unset: toReset,