Search code examples
reactjsroutesonclickcomponents

React useState not updating onclick event with <Link>


I unable to update the state of the variable in ReactJS on click of . It's works fine without route but when I add to="/myUrl" It isn't working below is my code

const [pageTitle, setPageTitle] = useState("Home");
  const updatePageTitleText = (newValue) => {
    setPageTitle(newValue);
  };

Routing List

 <div>
 <ul>
    <li>
      <Link onClick={() => updatePageTitleText("Home")} to="/">
        Home
      </Link>
    </li>
    <li>
      <Link onClick={() => updatePageTitleText("About")} to="/about">
        About
      </Link>
    </li>
    <li>
      <Link onClick={() => updatePageTitleText("Services")} to="/services">
        Services
      </Link>
    </li>
  </ul>
</div>

and find my component

 <Toolbar pageTitleProps={pageTitle} />

Solution

  • I think the best approach is to use the useLocation hook and remove the onClick event from Link, like this:

            import { useEffect, useState } from 'react';
            import { useLocation } from 'react-router-dom';
            const [pageTitle, setPageTitle] = useState("Home");
            let location = useLocation();
            useEffect(() => {
                    updatePageTitleText(location);
                }, [location]);
            const updatePageTitleText = (newValue) => {
                setPageTitle(newValue);
            };
            <Link to="/">
                Home
            </Link>