rafgraph / react-router-hash-link

Hash link scroll functionality for React Router
https://react-router-hash-link.rafgraph.dev
MIT License
732 stars 62 forks source link

Navigating to anchor within the same page causes state re-render #88

Closed mmillican closed 3 years ago

mmillican commented 3 years ago

Related to #83, I'm trying to use the <HashLink> within a single page to navigate to different sections of the page. No matter what I do, it is causing a re-render. Here's some relevant bits of the app:

Routes (shortened for brevity)

Note: This is wrapped in a <Router history={history} />

<Switch>
  <Route exact path="/login" component={Login} />
  <SecureRoute exact path="/profile" component={Profile} />
  <Route render={() => <Redirect to="/directory" />} />
</Switch>

Links (in a variety of flavors I've tried)

<li><HashLink to={'/profile#section-about'}>About</HashLink></li>
<li><HashLink to={'#section-about'}>About</HashLink></li>
<li><HashLink to="#section-contact">Contact Info</HashLink></li>
<li><HashLink to="/profile#section-contact">Contact Info</HashLink></li>

I have also tried using the scroll property with no luck.

I'm not sure it should affect it, but I do have a 0-dependency useEffect() hook on the page to load data.

rafgraph commented 3 years ago

This is likely not an issue with this library (just like #83).

Please create a minimal reproduction on https://codesandbox.io and I can take a look.

mmillican commented 3 years ago

I did the same things as you suggested in #83 with no luck. I will try to provide a reproduction shortly.

mmillican commented 3 years ago

@rafgraph While working on the repro, I think I narrowed it down it being the dependency-less useEffect() hook, shown below. Do you have any suggestions on how to get around this?


export default function Profile() {
    const [emp, setEmp] = useState({});
    const [isLoading, setIsLoading] = useState(false);

    const getEmployee = () => {
        EmployeeService.getCurrentEmployee().then(response => {
            setEmp(response);

            setIsLoading(false);
        }).catch(e => {
            setIsLoading(false);
            console.error(e);
            });
    };

    // on load get our employee
    useEffect(() => {
        setIsLoading(true);
        getEmployee();

     }, []);

}
rafgraph commented 3 years ago

Sorry not sure. If the components and markup remain the same, then simply updating state in useEffect shouldn’t be an issue, but I’m guessing the markup/components change based on the isLoading state, which is probably causing your issue. I don’t thinks this is an issue with this library.