React - ComponentDidUpdate

Hi,

I am using a conditional statement inside a ComponentDidUpdate function in a child component which is called in a parent component. How do i make sure that even if the same props are given twice it still updates.

I currently have sth like :

if (prevProps.x !== this.props.x)

however if i pass the same value twice from a parent, it does not re-render the second time as it just sees it as the same value. Any tips please?

Hi @Layooo,

If the prop value is the same, why would you want a render to trigger? This is one of the things React does for performance reasons, if a component is rendered with certain prop values and those prop values do not change, there should be no reason to re-render the component?

Can you explain more what you’re trying to do and why you’d want the component to re-render in the case where the prop value is not different?

Hi,

Thanks for responding. :grinning:

i am getting user input. So if the user enters the same value twice i want a re-render for each vale entered, i want it in such a way that each time a user enters a value a re-render occurs regardless of it’s the same value as the previously entered value

I have tried to achieve this without a conditional statement in the componentDidUpdate in the child component but if i don’t have a conditional statement it causes an infinite loop (this is because i change state in the componentDidUpdate as well so i need conditions otherwise it will be an infinite loop)

For some reference if you are able to check my code is here (lines 101 & 102) : https://codepen.io/Layoooo/full/NWRyvKY

We’re you able to work this out? I tried your CodePen and see if I click the same number twice I’m finding that the component does update.

If you’re still having an issue, maybe describe how to recreate it here.

Hi,

To recreate the issue please try doing operations with the LHS and RHS being that same value e.g. “5 x 5 = “ or “3 + 3 = “

I think the major issue is more with how the app is organized than with needing that component to re-render how you want it to. If you lift the calculation of the result up a level and just pass the result into the component that displays it as a prop you won’t have the issue you’re facing now.

Hi @Layooo,

A component usually re-renders whenever the parent re-renders. If the props you are passing are not from state and you want the child to update even if props haven’t changed, you should be using shouldComponentUpdate() life cycle method instead. ComponentDidUpdate() doesn’t determine whether a component should update or not. It is invoked after an update has occurred.

You can read more about shouldComponentUpdate() in the react doc.