import { useState, useEffect } from 'react';

/**
 * Hook to store the window hash as state, updating it on `hashchange` events.
 * Note that this hook stores the window hash _without_ the leading `#`
 * character. In general that's what we want, but you can obviously add the `#`
 * back in yourself if you need to.
 *
 * ```js
 *
 * import { useWindowHash } from '@politico/interactive-style';
 * ```
 */
const useWindowHash = function useWindowHash() {
  const [hash, setHash] = useState('');
  useEffect(() => {
    const changeHandler = () => {
      setHash(window.location.hash.slice(1));
    };
    changeHandler();
    window.addEventListener('hashchange', changeHandler);
    return () => {
      window.removeEventListener('hashchange', changeHandler);
    };
  }, []);
  return hash;
};
export default useWindowHash;