Use useEffect every time my Location.pathname is changed

Asked

Viewed 37 times

0

I have a variable called nameScreen that I need to change its value every time the location.path is changed (whenever there is a route change):

<Typography variant="h6" noWrap>
    {nameScreen}
</Typography>

I tried something like:

const [nameScreen, setNameScreen] = useState('')

const location = useLocation();

useEffect(() => {
    changeTitleHeader()
        // eslint-disable-next-line react-hooks/exhaustive-deps
},[location.pathname])

  const changeTitleHeader = () => {
      if (location.pathname === '/home') {
        setNameScreen('Welcome to home!')
      }
      else if(location.pathname === '/users') {
          setNameScreen('Users')
      }
      else if(location.pathname === '/companies') {
        setNameScreen('Companies')
      }
  }

I need every time my Location.pathname is changed, my nameScreen variable changes its value based on the route name.

Man useEffect() is not being called again when the location.pathname is changed. How can I fix this?

1 answer

0

The location.pathname is not a component state variable but, if you need that every time the component receives some change it recovers some value do not pass anything to the array of useEffect, example:

function Source() {
  const [st, setSt] = React.useState(new Date().toString());
  React.useEffect(() => {
    (() => {
      setSt(new Date().toString());
    })()
  });
  return (
    <h1>{st}</h1>
  );
}
function App() {
  const [input, setInput] = React.useState('');
  return (
    <div>
      <input type="text" value={input} onChange={e => setInput(e.target.value)} />
      <Source />
    </div>
  );
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

check that every time you type in input date and time are recovered. The logic in your code is the same, do not pass anything in useEffect, the tricky thing is to know if what you’re doing is the best solution, maybe it’s not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.