Skip to content

Instantly share code, notes, and snippets.

@rolandcoops
rolandcoops / memoize.js
Last active October 30, 2019 06:59
Small tree-based memoization module that handles any number of arguments (by reference). Slower than _.memoize (especially for multiple args), but with the advantage of computing keys based on all function arguments, not just the first.
const value = Symbol('value')
const retrieve = (node, path) => {
for (let i = 0; i < path.length; i++) {
const key = path[i]
if (node.has(key)) {
node = node.get(key)
} else {
const child = new Map()
node.set(key, child)
@rolandcoops
rolandcoops / useStableCallback.js
Created November 12, 2019 13:54
Custom React hook for creating a stable callback reference that can be passed down as prop
// Taken (with some minor changes) from:
// https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
import { useRef, useEffect, useCallback } from 'react'
const throwReferenceError = () => {
throw new ReferenceError('Callback was called directly while rendering, pass it as a callback prop instead.')
}
/**
@rolandcoops
rolandcoops / Form.jsx
Created December 2, 2019 13:32
Basic form event delegation example
import React, { useCallback, useState } from 'react'
const Form = () => {
const [profile, setProfile] = useState({
firstName: 'John',
lastName: 'Johnsonian',
jobTitle: 'Jabberwocky',
})
console.log(profile)