/react-state-url-fragment

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

Primary LanguageTypeScriptThe UnlicenseUnlicense

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