render react component when prop changes

Kourosh Neyestani picture Kourosh Neyestani · Mar 5, 2019 · Viewed 7.7k times · Source

how to force render our component when props changes? how to force render parent component when child component's props changes?

i searched a lot but all solutions are deprecated in new React version.

in my any pages (Route exact path="/post/:id" component={post}) for example (siteUrl/post/1) i am getting (:id) from props (this.props.match.params) and that works.

but when i am in single page component (Post) and this Route (siteUrl/post/1) when i am passing new Props to this component (:id).

props will changes but single component and parent component Will not re render...

Answer

Ali Sharifineyestani picture Ali Sharifineyestani · Mar 18, 2019

You may be using componentDidMount method.

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

but you need to use componentDidUpdate.

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

You can also use state and other React features without writing a class. read more: https://reactjs.org/docs/hooks-effect.html