ReactJS Flashcards
to learn reactjs (330 cards)
What is React?
React is an open-source frontend JavaScript library which is used for building user interfaces especially for single page applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.
What are the major features of React?
The major features of React are:
It uses VirtualDOM instead RealDOM considering that RealDOM manipulations are expensive.
Supports server-side rendering.
Follows Unidirectional* data flow or data binding.
Uses reusable/composable UI components to develop the view.
What is JSX?
JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.
In the example below text inside <h1> tag return as JavaScript function to the render function.
class App extends React.Component { render() { return( <div> <h1>{'Welcome to React world!'}</h1> </div> ) } }</h1>
What is the difference between Element and Component?
An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.
The object representation of React Element would be as follows:
const element = React.createElement( 'div', {id: 'login-btn'}, 'Login' ) The above React.createElement() function returns an object:
{ type: 'div', props: { children: 'Login', id: 'login-btn' } } And finally it renders to the DOM using ReactDOM.render():
<div>Login</div> Whereas a component can be declared in several different ways. It can be a class with a render() method. Alternatively, in simple cases, it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:
const Button = ({ onLogin }) => <div>Login</div> Then JSX gets transpiled to a React.createElement() function tree:
const Button = ({ onLogin }) => React.createElement( 'div', { id: 'login-btn', onClick: onLogin }, 'Login' )
How to create components in React?
There are two possible ways to create a component.
Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as first parameter and return React elements:
function Greeting({ message }) { return <h1>{`Hello, ${message}`}</h1> } Class Components: You can also use ES6 class to define a component. The above function component can be written as:
class Greeting extends React.Component { render() { return <h1>{`Hello, ${this.props.message}`}</h1> } }
When to use a Class Component over a Function Component?
If the component needs state or lifecycle methods then use class component otherwise use function component.
What are Pure Components?
React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.
What is state in React?
State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components. Let’s create an user component with message state,
class User extends React.Component { constructor(props) { super(props)
this.state = { message: 'Welcome to React world' } }
render() { return ( <div> <h1>{this.state.message}</h1> </div> ) } }
Difference between state and props
State is similar to props, but it is private and fully controlled by the component. i.e, It is not accessible to any component other than the one that owns and sets it.
What are props in React?
Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.
The primary purpose of props in React is to provide following component functionality:
Pass custom data to your component.
Trigger state changes.
Use via this.props.reactProp inside component’s render() method.
For example, let us create an element with reactProp property:
This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which originally already exists on all components created using React library.
props.reactProp
What is the difference between state and props?
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.
Why should we not update the state directly?
If you try to update state directly then it won’t re-render the component.
//Wrong this.state.message = 'Hello world' Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.
//Correct this.setState({ message: 'Hello World' }) Note: You can directly assign to the state object either in constructor or using latest javascript's class field declaration syntax.
What is the purpose of callback function as an argument of setState()?
The callback function is invoked when setState finished and the component gets rendered. Since setState() is asynchronous the callback function is used for any post action.
Note: It is recommended to use lifecycle method rather than this callback function.
setState({ name: ‘John’ }, () => console.log(‘The name has updated and component re-rendered’))
What is the difference between HTML and React event handling?
In HTML, the event name should be in lowercase:
Whereas in React it follows camelCase convention:
In HTML, you can return false to prevent default behavior:
<a></a>
Whereas in React you must call preventDefault() explicitly:
function handleClick(event) {
event.preventDefault()
console.log(‘The link was clicked.’)
}
How React works? How Virtual-DOM works in React?
React creates a virtual DOM. When state changes in a component it firstly runs a “diffing” algorithm, which identifies what has changed in the virtual DOM. The second step is reconciliation, where it updates the DOM with the results of diff.
The HTML DOM is always tree-structured — which is allowed by the structure of HTML document. The DOM trees are huge nowadays because of large apps. Since we are more and more pushed towards dynamic web apps (Single Page Applications — SPAs), we need to modify the DOM tree incessantly and a lot. And this is a real performance and development pain.
The Virtual DOM is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific implementation details. It is not invented by React but it uses it and provides it for free. ReactElements lives in the virtual DOM. They make the basic nodes here. Once we defined the elements, ReactElements can be render into the “real” DOM.
Whenever a ReactComponent is changing the state, diff algorithm in React runs and identifies what has changed. And then it updates the DOM with the results of diff. The point is - it’s done faster than it would be in the regular DOM.
What is JSX?
JSX is a syntax extension to JavaScript and comes with the full power of JavaScript. JSX produces React “elements”. You can embed any JavaScript expression in JSX by wrapping it in curly braces. After compilation, JSX expressions become regular JavaScript objects. This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions. Eventhough React does not require JSX, it is the recommended way of describing our UI in React app.
What is React.createClass?
React.createClass allows us to generate component "classes." But with ES6, React allows us to implement component classes that use ES6 JavaScript classes. The end result is the same -- we have a component class. But the style is different. And one is using a "custom" JavaScript class system (createClass) while the other is using a "native" JavaScript class system. When using React’s createClass() method, we pass in an object as an argument.
What is ReactDOM and what is the difference between ReactDOM and React?
Prior to v0.14, all ReactDOM functionality was part of React. But later, React and ReactDOM were split into two different libraries.
As the name implies, ReactDOM is the glue between React and the DOM. Often, we will only use it for one single thing: mounting with ReactDOM. Another useful feature of ReactDOM is ReactDOM.findDOMNode() which we can use to gain direct access to a DOM element.
For everything else, there’s React. We use React to define and create our elements, for lifecycle hooks, etc. i.e. the guts of a React application.
What are the differences between a class component and functional component?
Class components allows us to use additional features such as local state and lifecycle hooks. Also, to enable our component to have direct access to our store and thus holds state.
When our component just receives props and renders them to the page, this is a ‘stateless component’, for which a pure function can be used. These are also called dumb components or presentational components.
From the previous question, we can say that our Booklist component is functional components and are stateless.
Q6. What is the difference between state and props?
The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.
Props (short for properties) are a Component’s configuration. Props are how components talk to each other. They are received from above component and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data — callback functions may be passed in as props.
There is also the case that we can have default props so that props are set even if a parent component doesn’t pass props down.
Props and State do similar things but are used in different ways. The majority of our components will probably be stateless. Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed. State is used for mutable data, or data that will change. This is particularly useful for user input.
What are controlled components?
In HTML, form elements such as , , and typically maintain their own state and update it based on user input. When a user submits a form the values from the aforementioned elements are sent with the form. With React it works differently. The component containing the form will keep track of the value of the input in it’s state and will re-render the component each time the callback function e.g. onChange is fired as the state will be updated. A form element whose value is controlled by React in this way is called a “controlled component”.
With a controlled component, every state mutation will have an associated handler function. This makes it straightforward to modify or validate user input.
What is a higher order component?
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API. They are a pattern that emerges from React’s compositional nature.
A higher-order component is a function that takes a component and returns a new component. HOC’s allow you to reuse code, logic and bootstrap abstraction. HOCs are common in third-party React libraries. The most common is probably Redux’s connect function. Beyond simply sharing utility libraries and simple composition, HOCs are the best way to share behavior between React Components. If you find yourself writing a lot of code in different places that does the same thing, you may be able to refactor that code into a reusable HOC.
What is create-react-app?
create-react-app is the official CLI (Command Line Interface) for React to create React apps with no build configuration.
We don’t need to install or configure tools like Webpack or Babel. They are preconfigured and hidden so that we can focus on the code. We can install easily just like any other node modules. Then it is just one command to start the React project.
It includes everything we need to build a React app:
React, JSX, ES6, and Flow syntax support.
Language extras beyond ES6 like the object spread operator.
Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
A fast interactive unit test runner with built-in support for coverage reporting.
A live development server that warns about common mistakes.
A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
What is Redux?
The basic idea of Redux is that the entire application state is kept in a single store. The store is simply a javascript object. The only way to change the state is by firing actions from your application and then writing reducers for these actions that modify the state. The entire state transition is kept inside reducers and should not have any side-effects.
Redux is based on the idea that there should be only a single source of truth for your application state, be it UI state like which tab is active or Data state like the user profile details.
All of these data is retained by redux in a closure that redux calls a store . It also provides us a recipe of creating the said store, namely createStore(x).
The createStore function accepts another function, x as an argument. The passed in function is responsible for returning the state of the application at that point in time, which is then persisted in the store. This passed in function is known as the reducer.
This is a valid example reducer function:
This store can only be updated by dispatching an action. Our App dispatches an action, it is passed into reducer; the reducer returns a fresh instance of the state; the store notifies our App and it can begin it’s re render as required.
Hello!
{ messages.length > 0 && !isLogin?You have {messages.length} unread messages.
:You don't have unread messages.
}{`Welcome, ${this.props.name}`}
{`Age, ${this.props.age}`}
> ) } } Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.{'Something went wrong.'}
} return this.props.children } } After that use it as a regular component: ```{name}
{address &&{address}
}{name}
{address ?{address}
:{'Address is not available'}
}tag so that the formatting of the JSON.stringify() is retained: const data = { name: 'John', age: 42 } ``` class User extends React.Component { render() { return ({JSON.stringify(data, null, 2)}) } } ``` React.render(, document.getElementById('container'))
-
{employees.map(item => (
- {employee.name}-{employees.experience} ))}
{`Hello ${data.target}`}
)}/> Libraries such as React Router and DownShift are using this pattern.which is centered, red and sized at 1.5em const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; ` ``` // Create a component that renders a with some padding and a papayawhip background const Wrapper = styled.section` padding: 4em; background: papayawhip;
- Brad
- Brodge ``` ```
- Brandon
You clicked {count} times
setCount(count + 1)}> Click me ```Caught an error.
} returnSomething went wrong.
; } ``` return this.props.children; } }-
{props.items.map(item => (
// Without the `key`, React will fire a key warning
```
- {item.term}
- {item.description} ``` ))}
{name}
; This way you can prevent XSS(Cross-site-scripting) attacks in the application. ```Hello, world!
It is {new Date().toLocaleTimeString()}.
-
{props.pages.map((page) =>
- {page.title} )}
{page.title}
{page.content}
{page.pageNumber}
{content}
Hello, {this.props.name}
; } }); Note: If you use createReactClass then autobinding is available for all methods. i.e, You don't need to use .bind(this) with in constructor for event handlers. ```- first
- second
- first
- second
- third
- Duke
- Villanova
- Connecticut
- Duke
- Villanova
The mouse position is {mouse.x}, {mouse.y}
)}/> Actually children prop doesn’t need to be named in the list of “attributes” in JSX element. Instead, you can keep it directly inside element, {mouse => (The mouse position is {mouse.x}, {mouse.y}
)} While using this above technique(without any name), explicitly state that children should be a function in your propTypes. Mouse.propTypes = { children: PropTypes.func.isRequired };-
{data.hits.map(item => (
- {item.title} ))}