0

In react life cycle methods like

componentDidUpdate(prevState,prevProps)

doesn't gives error.
like if its a function it should give error like reference error.
What i understand in setState we pass prevState inside a callback function which internally assigns prevState object like in high order function but in case of componentDidUpdate i don't get this how this works under the hood.

  • are you calling componentDidUpdate yourself? or just defining a method on a class (which is the normal way to use componentDidUpdate)? Please show the context for this line of code. – Nicholas Tower Mar 09 '20 at 17:48
  • thank you for commenting, i am trying to understand how this function works. like when to use what here they are passing like variable and in setState they pass in callback function. – Parsuram Kailasa Mar 09 '20 at 17:53
  • should i assume it's a callback function as well which gets passed to some function which contains prevState and prevProps? – Parsuram Kailasa Mar 09 '20 at 17:57
  • Please read the docs carefully, `componentDidUpdate` is a lifecycle and not a function which you use in the component instance. – Dennis Vash Mar 09 '20 at 18:31
  • @DennisVash yes sir, i was asking how it works i am tiered of rules after rules. – Parsuram Kailasa Mar 09 '20 at 18:37
  • Could you read the docs on it https://reactjs.org/docs/react-component.html#componentdidupdate and maybe ask something from there that's not clear? – kmui2 Mar 09 '20 at 18:51

1 Answers1

0

componentDidUpdate() is called after componentDidMount() which is called after render. All lifecycle methods are called in order with render() in the middle. They are all defined as empty until you define them as something else.

componentDidUpdate is used to check if a state or prop has changed. If a paticular state changed you might have an API that needs to be called to up a counter for example.

See this for more info on componentDidUpdate: https://dev.to/cesareferrari/how-to-use-componentdidupdate-in-react-30en

Greg M
  • 398
  • 1
  • 9
  • thank you for replying, i was asking is how it works under the hood. like is it callback function which. here we are passing some variable or rather an object then this function would have gave an reference error. – Parsuram Kailasa Mar 09 '20 at 18:21
  • I don't think it is a callback function. If anything they operate similar to hooks in the new version of react. If you look at the react repo on github you will see that when a state is changed, the lifecycle methods are queued and added to a scheduler. The current state and next state is stored. After `render()` current state -> prev state and next state -> currentState. (render is a lifecycle method).` ComponentDidUpdate()` is than called and passed by value the prev state and also has access to the current state via `this.state` – Greg M Mar 09 '20 at 20:18