DEV Community

spencer-w-mathews
spencer-w-mathews

Posted on

Information Flow in React.js

Why is information flow in React.js different from JavaScript?
In traditional JS programming a single page document was used to accomplish all actions. This means scope of variables is the only barrier for communication from function to function. React.js allows the use of components which significantly increase the organization and readability of the JavaScript in the application. React.js grants the ability to make a component hierarchy or tree of components. This tree of components need a way of communicating with each other.

How to pass information down the tree
Information passes from the parent component to child component with the use of props.
These props have to be passed to child:

import React from "react"
import Child from "./Child"

function Parent(){
const x="this is from my parent"
return(
   <Child x={x}/>
)
}

export default Parent;
Enter fullscreen mode Exit fullscreen mode

Then, accepted by the child:

import React from "react"

function Child({x}){
return(
   console.log(x)
)
}

export default Child;
Enter fullscreen mode Exit fullscreen mode

The console.log in this Child component would output the string assigned to x from the parent function.

How to pass information back up the tree
Passing information back up the tree otherwise known as inverse data flow gets a little more complicated. To do this a function from the parent component must be passed to the child and then called with the data needed in the parent component.

import React from "react"
import Child from "./Child"

function Parent(){
  function getName(nameFromChild){
    console.log(name)
  }
return(
   <Child getName={getName}/>
)
}

export default Parent;
Enter fullscreen mode Exit fullscreen mode

Then, accepted by the child:

import React from "react"

function Child({getName}){
  const name="Steve"
  getName(name)
}

export default Child;
Enter fullscreen mode Exit fullscreen mode

This will return a console.log of "Steve".

Conclusion
The woes of information flow may seem daunting at first. After passing hundreds of props and callback functions up and down component trees it feels like second nature, and the gains you receive in terms of organization and readability far outweigh the slight learning curve. Thank you for reading!!!

Top comments (0)