Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
How do I get smooth scroll and scroll snap to work together in React while also persisting user scroll position on refresh?

I have a custom hook that persists the user's scroll position on page refresh. I also want to implement smooth scrolling for my navigation links (site is a single page, brochure design).

My custom hook works on its own, but adding scroll-behavior: smooth to the root html element breaks everything. Similarly, if my window.scrollTo() call utilizes behavior: 'smooth' the user is sent to the top of the page on refresh regardless of if I have scroll-behavior: smooth included or not.

The custom hook is as follows:

const usePersistScrollPosition = (key) => {
  const [position, setPosition] = useLocalStorage(key, 0)
  useEffect(() => {
    window.scrollTo(0, position);
    return () => {setPosition(window.scrollY)}
  }, [])
  return position
}

// Hook taken from https://usehooks.com/useLocalStorage/

const useLocalStorage = (key, initialValue) => {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });
  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue = (value) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }
  };
  return [storedValue, setValue];
};

The CSS: (Taken from this CSS tricks article)

html {
  scroll-snap-type: proximity;
  scroll-snap-points-y: repeat(100vh);
  scroll-snap-type: y proximity;
  /* scroll-behavior: smooth; */
  overflow-y: scroll;
  overflow-x: hidden;
  max-width: 100vw;
}

What's the best way to utilize smooth scrolling combined with scroll snapping? I also tried using the react-scroll library but also ran into some difficulties there.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda