re-render component on url change

Viewed 536

I'm new to react and I have some trouble re-rendering a component. I have the CodeFeed component with route /code/feed?user_id=${id} which displays a list with users' posts. This list can be filter by the user_id. In case user_id is undefined, the posts of all users will be displayed.

On my navbar I have two links: Code Feed(which displays the posts for all users) and My Codes(which displays the codes for the current session user).

If an user clicks on Code Feed(/code/feed) the component will render and display the list with all users' posts, but if the user clicks right after on My Codes(/code/feed?user_id=session_user) there will remain the content from Code Feed because the component will not render again to display the new content. In order to display the new content, the component has to get the new user_id from the url, but it gets it only if the component is rendered again.

I was thinking about using the state and changing the value of id from the route. I'm using the useEffect() hook and I tried to re-render the component by passing to the second argument the id. The problem is that I don't know when it's the right time to change the value of id in order to change the state of the component so I can trigger the rendering.

Here's my component and what I tried to do so far: https://gist.github.com/dayanamdr/2ac0880aa4d5f969658a6ffede3479bb

2 Answers

To rerender the same page with new data change key

Set a new key on the same "template" and the page will remount as a new component. This should give you the desired effect.

The key in react marks a unique component, that's why it's mandatory in lists, so that react can track where each component is easily. By changing the key on a component it is identified as a new component and therefore will unmount the old and mount the new. This a helpful when swapping pages that use the same component. Of course it's heavier than swapping just some components, but if your page is not super heavy you shouldn't have issues with this method.

const myPage = (props) => {
  
  return (
    <div key={props.uid}>
      {props.children}
    </div>
  )
}

The page only re-renders when it's state or props change . You can change some state inside the component to trigger re-rendering .

Related