Last active
March 30, 2023 06:51
-
-
Save mike-at-redspace/07e376ffa23f8014ed808eaefa005a9e to your computer and use it in GitHub Desktop.
Poorman's hashrouter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} /> | |
); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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