Common Hooks
Working React Hooks examples — a stale-closure-proof counter and a custom useResizeObserver — plus when useReducer replaces Redux and why ResizeObserver beats IntersectionObserver.
From the first watching of Reactconf 2018 keynote, where [Hooks](link here) were first introduced I was taken aback by the simplicity of the approach but the far reaching applicability to solving common problems within design and build of react applications. It was very reminicent of quote from Albert Einstein:
Everything should be made as simple as possible, but not simpler
Which is funny in light of Dan Ambramov's comment about Hooks being the electron in Reacts Atom logo. This article will serve as a library of ramblings about personally developed, as well as externally discovered hook use-cases for future project usage and reference.
Principles
The fundamental tenants of React Hooks seems to be to enable a cleaner and more functional mechanism for accessing the underlying core react tools, including: state, context,lifecycle, and refs. With this new API, we can go about implementing a simpler, lighter, and likely more modular approach to problems we'd normally seek Redux/Redux-sagas to solve. I would like to see how hooks compare when building out a larger app, in comparison to experiences with Redux. To validate the excitement felt about the future of React.
The primary hooks available are the following:
- useState - provides getter/setter pair for managing a localised state
- useEffect - accepts a function that will possibly effectuate aspects of a component. Example could be to do some kind of mutation, logging, delayed action or timer and other side effects within this hook. By default effects run on every complete render, but more granular firing can be controled via the second argumement.
- useContext - Takes a context object and returns the current value of the given context. If the given context changes, the component will re-render.
- useReducer - Alternative to the useState hook, accepts a reducer of type
(state, action) => newState, very similar to model to howReduxoperates. Returns the current state, paired with adispatchmethod.
There are a number of more advanced hooks which we'll cover in more detail over time.
Examples
Here we define common hook usages across the number of fundamental categories.
useState
counter
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(c => c + 1)}>
Click me
</button>
</div>
);
}Note the functional updater form setCount(c => c + 1) rather than setCount(count + 1). Passing a function avoids stale closures by always operating on the latest state value instead of the count captured at render time.
useEffect
useResizerObserver
Provides a mechanism to fetch element size using the ResizeObserver API. Note that this is the correct API for observing dimensions. The Intersection Observer API tracks element visibility, not size.
useResizerObserver.tsx
import { useEffect, useState, useRef } from 'react';
import ResizeObserver from 'resize-observer-polyfill';
export default function() {
const isClient = typeof window === 'object';
const ref = useRef();
const [width, changeWidth] = useState(1);
const [height, changeHeight] = useState(1);
useEffect(() => {
const element = ref.current;
if (!element || !isClient) {
return;
}
const resizeObserver = new ResizeObserver(entries => {
if (!Array.isArray(entries)) {
return;
}
if (!entries.length) {
return;
}
const entry = entries[0];
changeWidth(entry.contentRect.width);
changeHeight(entry.contentRect.height);
});
resizeObserver.observe(element);
return () => resizeObserver.disconnect();
}, [width, isClient]);
return [ref, width, height];
}
Try it in the lab
All effects →Band Structure
physicsNearly-free electron E-k diagram with Brillouin zone gaps.
condensed mattersolid stateTransmission Line Pulse
engineeringTDR — a voltage pulse travels, reflects, and inverts on a mismatched line.
rftdrimpedanceWave Superposition
physicsInterference of two plane waves — beats, standing waves, and nodes.
wavesinterference
More from the blog
Attention, From the Inside Out
Attention is just a weighted average whose weights the data computes by asking itself questions. A worked tour through scaled dot-product attention, temperature and sampling, and what a representative 46B-active / 1T-total Mixture-of-Experts spec actually means — with live matrices you can poke.
PLL Design from First Principles
A phase-locked loop is a control system with a phase detector instead of a summing junction. The intuition you can build with the lab above is more durable than the textbook derivations.
The Smith Chart is Geometry
What looks like a chart for radio engineers is really a Möbius transform drawn on the complex plane. A visual essay on why impedance matching is a question of circles, lines, and rotations.