Sam
Sam

Reputation: 30388

Triggering a function call on state change

I have a reusable and general purpose date picker component that is used in other components. In some cases, there are multiple instances of the date picker component in a single parent component.

Here's my question: how do I trigger a function call that is inside the parent component when the state changes?

I think giving you the actual scenario will help clarify what I'm trying to accomplish.

Please keep in mind that the date picker is a general purpose component so the usage scenarios differ significantly.

In some cases, when the user clicks to select the date, I need to get some data from the back-end API. For example, when the user clicks a particular date, I may have to retrieve all the items in the user's calendar for that date.

I'm trying to keep all non-date-picker concerns out of the date picker component which I think is the right way to do this. However, as you can see in above example, in some cases, a user action within the date picker needs to trigger a call to a function that is outside of the date picker component.

One way I can think of handling this is to pass the function to the date picker as a prop and call it when certain conditions are met.

I thought another approach could be to detect state change in the parent component and call a function -- provided that there's a way for me to trigger function calls on state changes.

Is this possible AND a good way to handle this scenario?

Upvotes: 1

Views: 822

Answers (1)

Chris Hawkes
Chris Hawkes

Reputation: 12410

"Is it possible to detect a state change and call a function when it happens?"

In a sense, this is exactly what React does to trigger a new DOM render every time dependent state is updated. As you've already stated, I've seen most people solve your dilemma by having a custom change handler passed down to your date component from the parent component which will listen for changes and take the appropriate action.

You could also have default functionality which is handled by the component and overridden should a function prop be passed to it. I would suggest this route as it keeps the date component as dumb as possible to custom logic and provides the ability to pass custom functionality when needed.

Upvotes: 1

Related Questions