preface

Before I learned React hooks, I was skeptical that the function component could really replace the class component. Can a long-written class component really be replaced by a function component?

The fact is, after using react hooks: Smells good! Never want to write a class component again.

If you want to learn react hooks, check out the nuggets website.

The reason for writing this article is that when using react-router, switch routes through history.push or Link. If the component scroll bar is too high, when entering the next page, Remember that the page scroll bar remains the same height as the previous page scroll bar (if the current page is also higher than the screen height). There are many simple ways to fix this, including writing two React hooks methods that can be reused elsewhere.

Switch routes back to the top

If we don’t want to switch routes and go to the next page with the same scroll bar as the previous one, most of the time we want the page to go back to the top, assuming our code looks like this.

import React, { useEffect } from "react";
import { BrowserRouter as Router, Link, Switch, Route } from "react-router-dom";
import { useLocation } from "react-router";  //v5.1.2

const App = () => {
  return (
    <Router>
      <div style={{position: 'fixed', right: 0 , top: '50%'}}>
        <ul>
          <li>
            <Link to="/public">Public Page</Link>
          </li>
          <li>
            <Link to="/protected">Protected Page</Link>
          </li>
        </ul>
      </div>
      <Home />
    </Router>
  );
};

const Home = () => {
  return (
    <Switch>
      <Route path="/public">
        <PublicPage />
      </Route>
      <Route path="/protected">
        <ProtectedPage />
      </Route>
    </Switch>
  );
};

const PublicPage = () => {
  return (
    <div style={{ height: 5000, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
      <h1>PublicPage</h1>
      <h1>PublicPage</h1>
      <h1>PublicPage</h1>
      <h1>PublicPage</h1>
      <h1>PublicPage</h1>
      <h1>PublicPage</h1>
    </div>
  );
};

const ProtectedPage = () => {
  return (
    <div style={{ height: 5000, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
      <h1>ProtectedPage</h1>
      <h1>ProtectedPage</h1>
      <h1>ProtectedPage</h1>
      <h1>ProtectedPage</h1>
      <h1>ProtectedPage</h1>
      <h1>ProtectedPage</h1>
    </div>
  );
};
    
Copy the code

ProtectedPage
/protected

public
public
useScrollToTop

Const useScrollToTop = () => {// Note that custom Hooks define useXXX const {pathName} = useLocation(); useEffect(() => { window.scrollTo(0, 0); }, [pathname]);return null;
};

//
Copy the code

Use in code:

const Home = () => {
  useScrollToTop();  
  return (
    <Switch>
      <Route path="/public">
        <PublicPage />
      </Route>
      <Route path="/protected">
        <ProtectedPage />
      </Route>
    </Switch>
  );
};
Copy the code

The Home component listens for pathName changes, performs side effects, and brings the page back to the top. It can also be used in components alone, only when the page is mounted back to the top:

const useScrollToTop = () => { const { pathname } = useLocation(); useEffect(() => { window.scrollTo(0, 0); } []); // equivalent to componentDidmountreturn null;
};
Copy the code

Restores the scroll bar position

If we want to remember the position of the scroll bar on the previous page, we can change it to the next access after the jump:

const useReStoreScrollTop = () => {
  const { pathname } = useLocation();
  useEffect(() => {
    try {
      let scrollY = sessionStorage.getItem(pathname)
      scrollY && window.scrollTo(0, scrollY)
    } catch (error) {
      throw error
    }
    return() => {try {sessionstorage.setitem (pathname, window.scrolly)} catch (error) {// SrcollTop throw error}} for a specific DOM element; }, [pathname]) }Copy the code

Use the sessionStorage to save the scrolling position of the page when the component is uninstalled, and read the value of sessionStorage when the page is mounted to restore the previous position.








Here are just two simple examples, the actual business may be more complex, readers need to consider more boundary cases.

conclusion

React hooks solve the problem of sharing state logic between components, eliminating nesting of higher-order function components, providing the benefit of finer granularity, clearer code, and not needing to care about the component lifecycle, only the side effects of data changes. You’ll love React Hooks after writing Function Component.