Published
Edited
Mar 14, 2021
6 stars
Insert cell
Insert cell
Insert cell
Insert cell
function useKeyPress(fn) {
useEffect(() => {
window.addEventListener("keypress", fn);
return () => window.removeEventListener("keypress", fn);
}, [fn]) // <- 'fn' is in the dependencies
}
Insert cell
Insert cell
{
return function Component() {
useKeyPress(() => {
console.log("Some key was pressed");
});

return null;
}
}
Insert cell
Insert cell
{
function onKeyPress() {
console.log("Some key was pressed");
}
return function Component() {
useKeyPress(onKeyPress);

return null;
}
}
Insert cell
Insert cell
{
return function Component(props) {
const { id } = props
useKeyPress(useCallback(() => {
console.log(`Some key was pressed (handled in component ${id})`);
}, [id]));

return null;
}
}
Insert cell
Insert cell
function useBetterKeyPress(fn) {
// Create a ref which keeps a reference to the current version of the callback.
const ref = useRef(fn)
ref.current = fn
useEffect(() => {
function onKeyPress() {
// Invoke whatever callback the ref is currently pointing to.
ref.current()
}
window.addEventListener("keypress", onKeyPress);
return () => window.removeEventListener("keypress", onKeyPress);
}, []) // <- no dependencies!
}
Insert cell
Insert cell
Insert cell
function useKeyPressOptions(fn, options = { delay: 0 }) {
const ref = useRef({ fn, options })
ref.current = { fn, options }
useEffect(() => {
function onKeyPress() {
setTimeout(ref.fn.current, ref.options.delay)
}
window.addEventListener("keypress", onKeyPress);
return () => window.removeEventListener("keypress", onKeyPress);
}, [])
}
Insert cell
{
return function Component(props) {
const { id, delay } = props
useKeyPressOptions(() => {
console.log(`Some key was pressed (handled in component ${id}, after delay ${delay}ms)`);
}, { delay })

return null;
}
}
Insert cell
Insert cell
Insert cell
import { useState, useEffect, useCallback, useRef, component, jsx, render } from "@j-f1/react"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more