Once upon a time, users had to refresh pages to see new posts and notifications on social media. The same for receiving any kind of updates. No one really thought about it, but Facebook realized there was a room for improvement. They launched React and web development was never the same again. Thanks to React, UX has dramatically improved and users set higher expectations every year.
These days, React is the most popular library for building interactive user interfaces. In this article, we will look at most important concepts in React.
React maintains a shadow copy of the DOM. Data displayed on the page is stored in the state and props. Whenever any data changes, React calls the render() method to update the page.
Virtual DOM is very efficient, so it can afford to update the entire component tree. Then React compares virtual DOM with the real DOM and settles differences. This ensures efficiency of the web application. It also ensures that web applications always display the most recent updates.
State, props, single-way data flow
In React, state is the object that stores current ‘status’ of the component. For example, if a new post needs to be displayed, the id of the new post would be added to the state. As you know, changes in the state (and props) also triggers update of the page.
State is often used for dynamic functionalities. For example, dynamic rendering of certain elements or components. State values are also used to conditionally style elements using inline styles or className values.
React recommends to store state data in the component at the top of the tree. This is called a ‘single source of truth’. Every component in a web application should receive data from the main parent component.
Finally, this brings us to props. This is how parent component passes data down to children components. In JSX, you can define props as simple custom attributes on React elements and custom components. Props can be passed from parent components to children, not the other way round. This is called single-way data flow.
In JSX, you can conditionally display error messages, or even hide entire components depending on state values. You can’t use getElementById() method, but you can use refs to the same effect. SimpleFrontEnd had a great article on using refs to scroll to a specific element in JSX: