Skip to content

Instantly share code, notes, and snippets.

@mike-at-redspace
Last active March 30, 2023 06:51
Show Gist options
  • Save mike-at-redspace/07e376ffa23f8014ed808eaefa005a9e to your computer and use it in GitHub Desktop.
Save mike-at-redspace/07e376ffa23f8014ed808eaefa005a9e to your computer and use it in GitHub Desktop.
Poorman's hashrouter
import useRememberState from './useRememberState';
const MyComponent = () => {
const [value, setValue] = useRememberState('myKey', 'defaultValue');
const handleChange = event => {
setValue(event.target.value);
};
return (
<input type="text" value={value} onChange={handleChange} />
);
};
import { useState, useEffect } from 'react';
const useRememberState = (key, initialValue) => {
const [state, setState] = useState(() => {
const value = window.location.hash.match(new RegExp(`#${key}=([^&]*)`));
return value ? decodeURIComponent(value[1]) : initialValue;
});
useEffect(() => {
window.addEventListener('hashchange', handleHashChange);
return () => window.removeEventListener('hashchange', handleHashChange);
}, []);
const handleHashChange = () => {
const value = window.location.hash.match(new RegExp(`#${key}=([^&]*)`));
setState(value ? decodeURIComponent(value[1]) : initialValue);
};
const updateState = newState => {
const newHash = `#${key}=${encodeURIComponent(newState)}`;
if (window.location.hash === newHash) return;
window.history.replaceState(undefined, '', `${window.location.pathname}${window.location.search}${newHash}`);
setState(newState);
};
return [state, updateState];
};
export default useRememberState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment