Skip to content

Instantly share code, notes, and snippets.

@webbower
Last active November 1, 2023 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webbower/b1a617ae247ebac4de2a6ec8c7d3ca32 to your computer and use it in GitHub Desktop.
Save webbower/b1a617ae247ebac4de2a6ec8c7d3ca32 to your computer and use it in GitHub Desktop.
Custom hooks
import { useState, useRef } from 'react';
// Can't use React State because setting the constant to a function will execute that function in `useState`
// const useConstant = value => useState(value)[0];
const useConstant = value => useRef(value).current;
const myConst = useConstant('foo');
import { useEffect } from 'react';
export const useEffectOnMounted = cb => {
useEffect(cb, []);
};
import { useState, useRef } from 'react';
// WIP
const useFormState = (stateShape = {}) => {
const [formState, setFormState] = useState(stateShape);
const api = useRef({
setFieldValue(fieldName, fieldValue) {
if (!stateShape.hasOwnProperty(fieldName)) {
throw new Error('...');
}
setFormState({
...formState,
[fieldName]: fieldValue,
});
},
handleFieldChange(ev) {
setFieldValue(ev.target.name, ev.target.value);
},
handleFieldValueChange(newValue, ev) {
setFieldValue(newValue, ev.target.name);
},
});
const { setFieldValue, handleFieldChange } = api.current;
return [formState, setFieldValue, handleFieldChange];
};
import { useRef } from 'react';
const useScrollManagement = () => {
const scrollLockState = useRef({
scrollPosition: null,
});
const lockScroll = () => {
scrollLockState.current = {
scrollPosition: window.scrollY,
};
window.scrollY = 0;
document.body.style.setProperty('overflow', 'hidden');
};
const unlockScroll = () => {
document.body.style.removeProperty('overflow');
window.scrollY = scrollLockState.current.scrollPosition;
scrollLockState.current = {
scrollPosition: null,
};
};
return { lockScroll, unlockScroll };
};
export default useScrollManagement;
import { useState, useRef } from 'react';
const useToggleState = (initialState = false) => {
if (typeof initialState !== 'boolean') {
throw new TypeError(`useToggleState expects initialState to be boolean. ${initialState} given.`);
}
const [state, setState] = useState(initialState);
const api = useRef({
on: () => setState(true),
off: () => setState(false),
toggle: () => setState(current => !current),
});
return [state, api.current];
};
const [isVisible, { on: show, off: hide }] = useToggleState();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment