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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more