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).


(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…

(Evan G) #3

I want the opposite actually. Consider the following case:

  1. Main app gets some data from a remote server.

  2. Main app tells sub-component B to print out “Success” to its output. Component B is like a console log, printing each new message for the user to see.

The “Success” message needs to be sent only once, after the API has finished successfully, no need to keep it in a state, or re-send it via props on every app refresh.

In other words, I want to send messages/events to component B when something happens in the app, but only once. Without storing them in app state or keeping track of them outside that component.

Makes sense?

(Mikayel) #4

As I understand you are trying to take vanilla javascript path in react.
React requires top-down data flow and composite pattern. I will recommend to move all logic to root component and use sub component for view only, in this case the sub component will get props and will print.