Skip to content

🧩 Persists react state as a url fragment to enable navigation between application states

License

Notifications You must be signed in to change notification settings

iamogbz/react-state-url-fragment

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React State Url Fragment

NPM badge Dependabot badge Dependencies Build Status Coverage Status

Sets react state to url fragment

useUrlState

import { useCallback } from "react";
import { useUrlState } from "react-state-url-fragment";

export function usePageState<T>(defaultState?: T) {
  const getEncodedState = useCallback(() => location.hash.substring(1), []);
  const onEncodedState = useCallback((hash) => (location.hash = hash), []);
  const handleDecodeError = defaultState && (() => defaultState);

  return useUrlState<T>({
    getEncodedState,
    handleDecodeError,
    onEncodedState,
  });
}

Example

$ cd demo/
$ make start

Starting the development server...

Check it out here