Yogesh Chauhan's Blog

Data Flows in React

in React on April 28, 2021

In React, there is no way a parent element or a child element knows if any component is stateful or stateless. They are unaware of the states and they really don’t care if it’s a function or a class.

In React, state is called local or encapsulated.

That’s because the state of any component is not accessible by any other component. It is only accessible and set/changed by the component who owns it.

But you can pass the state as props to its childs. For e.g.



<FormattedDate date={this.state.date} />


This is how FormattedDate component will receive it:



function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}


The FormattedDate component doesn’t know about date‘s origin. Maybe it’s from the Clock’s state, or from the Clock’s props, or it was just typed manually — only we know because we’ve passes it as an argument.

It is known as a “top-down” or “unidirectional” data flow where state is owned by specific component and UI derived from that state can have effect on the components below in the tree structure.

The components are defined as a waterfall. When you add a new state, it just joins at that point and stays in the flow going downwards.

Here’s a great example of how each component is managed separately (isolated) by React.

As you can see, each rendered Clock component creates its own specific UI even though they are coming from same component. The UI is getting updated independently.

Source: React Docs


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
first-of-type and last-of-type selectors in CSSCSSCrypto.getRandomValues() method in JavaScriptJavaScriptHow to pass arguments in SCSS function?SCSSbin2hex() and chr() String Functions in PHPPHPWordPress: How to access first and random row values from a repeater field in ACF?WordPressList of social media icon logo color codes in HEXMiscellaneous