Wednesday, November 10, 2021

How React component pass data around

For React components, the basic way to receive data is passing them as component attributes when creating the component in its parent's html render method. Those attributes will pass into the component's js file as props parameter.

Within the component js file's render method, internal data can be handled by useState hook, which update the user input into component state, which leads to update the ui.

In case when a react component needs to pass data out to its parent, the parent can pass a callback method to the component as a component attribute, then when some event happens, the component can call the callback method and pass the data as callback parameter. Then the parent component can use the callback method's implementation to handle the data specified in the callback method's parameters. For example, the parent can update its own data managed by the useState hook. 

To avoid passing property value from top to low layer components, react application can use useContext to facilitate passing data directly from top component to lower layer components.


No comments:

Post a Comment