Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.memo with react-router-dom useLocation()

Recently I found some performance issue with my React app, and after some research i discovered React Memo. Some training examples worked as excepted, but when connect it into my app it does not have any effect. I found that problem is with useLocation.

const Table = React.memo(() => {
 
    const location = useLocation();

    return <div>something</div>
    
},(prevProps, nextProps) => {
    return true //I dont want re-render this Component when parent component is re-rendered
}) 

Without useLocation it workes, but I need this location, because based on this location, more specifically based on filters from this location i call API data. Something like

const location = useLocation();
  useEffect(() => {
    dispatch(getData(location.search))
}, [location]);

Have someone better solution or some tips?

like image 238
Mormen Avatar asked Jun 24 '26 20:06

Mormen


1 Answers

The solution around this would be to create a wrapper that passes location in as a prop. Doing so will make table a pure component and will only rerender when location changes.

function TableWrapper(){
  const location = useLocation()

  return <Table location={location} />
}

then table will need to have location as a prop

const Table = React.memo(({location}) => {
    return <div>something</div>
}) 
like image 189
Jaxon Porter Avatar answered Jun 27 '26 10:06

Jaxon Porter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!