Skip to content

Instantly share code, notes, and snippets.

View andycarrell's full-sized avatar

Andy Carrell andycarrell

View GitHub Profile
import { useEffect, useState } from "react"
let singletonState = null;
function useSingleton() {
const [internalState, setInternalState] = useState(singletonState);
useEffect(() => {
if (singletonState !== internalState) {
setInternalState(singletonState)
useDidUpdate(callback, next, initialState) {
const previous = React.useRef(initialState)
callback(previous.current, next)
React.useEffect(() => {
previous.current = next
})
}
import { useEffect, useState } from "react";
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
const TileWrapper = WrappedComponent => {
const WrapperComponent = props => {
const { getTile: fetchTile, match, tile } = props;
const tileId = match.params.tileId
? parseInt(match.params.tileId, 10)
: null;
React.useEffect(() => {
fetchTile({ id: tileId });
}, []);
import React, { useEffect, useState } from "react";
import { MockedProvider } from "react-apollo/test-utils";
const ReRenderMockedProvider = ({ children, mocks }) => {
const [key, setKey] = useState(Date.now());
useEffect(() => {
setKey(Date.now());
}, [mocks]);
return (
import styled from "styled-components/macro"
export const Dont = props => <sup {...props} />
export const Super0 = styled.span`
vertical-align: baseline;
position: relative;
top: -0.4em;
font-size: smaller;
line-height: 0;
function useTimeout() {
const ids = React.useRef([]);
React.useEffect(() => () => ids.current.forEach(clearTimeout), []);
// setTimeout takes a callback and a delay, then returns the id associated with the timeout.
const _setTimeout = React.useCallback((callback, delay) => {
const id = setTimeout(callback, delay);
ids.current.push(id);
const withFormikField = F => {
const HoC = ({ name, onBlur, onChange, ...rest }) => {
const handleChange = value => onChange({ target: { name, value } });
const handleBlur = () => onBlur({ target: { name } });
return <F {...rest} onChange={handleChange} onBlur={handleBlur} />;
};
return HoC;
};
const SelectForFormik = withFormikField(Select);
const [hasCheckedSession, setHasCheckedSession] = useState(false);
useEffect(() => {
if (hasCheckedSession) {
return;
}
if (!sessionToken) {
setHasCheckedSession(true);
return;
function useStorageListener(key, onChange) {
useEffect(() => {
function handleChange({ key: eventKey, newValue }) {
if (eventKey === key) {
const parsed = newValue && JSON.parse(newValue);
onChange(parsed);
}
if (!eventKey) {
onChange(getLocalStorageItem(key));
}