Tracks the browser's location hash value, and allows changing it.
useState()
hook to lazily get the hash
property of the Location
object.useCallback()
hook to create a handler that updates the state.useEffect()
hook to add a listener for the 'hashchange'
event when mounting and clean it up when unmounting.useCallback()
hook to create a function that updates the hash
property of the Location
object with the given value.const useHash = () => {
const [hash, setHash] = React.useState(() => window.location.hash);
const hashChangeHandler = React.useCallback(() => {
setHash(window.location.hash);
}, []);
React.useEffect(() => {
window.addEventListener('hashchange', hashChangeHandler);
return () => {
window.removeEventListener('hashchange', hashChangeHandler);
};
}, []);
const updateHash = React.useCallback(
newHash => {
if (newHash !== hash) window.location.hash = newHash;
},
[hash]
);
return [hash, updateHash];
};
const MyApp = () => {
const [hash, setHash] = useHash();
React.useEffect(() => {
setHash('#list');
}, []);
return (
<>
<p>window.location.href: {window.location.href}</p>
<p>Edit hash: </p>
<input value={hash} onChange={e => setHash(e.target.value)} />
</>
);
};
ReactDOM.render(<MyApp />, document.getElementById('root'));
React, Hooks
Tracks the browser's location search param.
React, Hooks
Tracks the dimensions of the browser window.
React, Hooks
Returns a stateful value, persisted in localStorage
, and a function to update it.