Send a message, or invoke a function, to a Component, once!


(Evan G) #1

Alright, I am twisting my brain a bit on this one…

I have a component, think of it as a console log/output, or a user notification component. I want to send messages to it, one at a time (e.g. when other stuff happens elsewhere in the app, I want to print out a new message to the component).

It’s very easy to create a Javascript function that accepts a string input, and does something with it, because you call it once when you need it, and you’re done.

With React and props/state however, the parent component will keep re-sending the data on each app refresh. And the user may be seeing an expired message, presented as new.

So I need a simple and clear way to deal with this design pattern, without creating too much complexity in the component, or the parent (especially when it’s 2-3 levels above).

Thanks


(Mikayel) #2

Create your function in your top component and pass down the function as a prop and then in child component call the function.

One other way is to pass down the function via context, but I will not recommend to use context in this case…