React 3of4 Flashcards
#201-300
<p></p>
<p></p>
<p>Why React tab is not showing up in DevTools?</p>
<p></p>
<p></p>
<p>When the page loads, React DevTools sets a global named \_\_REACT_DEVTOOLS_GLOBAL_HOOK\_\_, then React communicates with that hook during initialization. If the website is not using React or if React fails to communicate with DevTools then it won't show up the tab.</p>
<p></p>
<p></p>
<p>What are Styled Components?</p>
<p></p>
<p></p>
<p>styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.</p>
<p></p>
<p></p>
<p>Give an example of Styled Components?</p>
<p></p>
<p></p>
<p>Lets create and components with specific styles for each.
<br></br>
<br></br>import React from 'react'
<br></br>import styled from 'styled-components'
<br></br>
<br></br>// Create a component that renders an </p>
<h1> which is centered, red and sized at 1.5em
<br></br>const Title = styled.h1`
<br></br> font-size: 1.5em;
<br></br> text-align: center;
<br></br> color: palevioletred;
<br></br>`
<br></br>
<br></br>// Create a component that renders a with some padding and a papayawhip background
<br></br>const Wrapper = styled.section`
<br></br> padding: 4em;
<br></br> background: papayawhip;
<br></br>`
<br></br>These two variables, Title and Wrapper, are now components that you can render just like any other react component.
<br></br>
<br></br>
<br></br> {'Lets start first styled component!'}
<br></br></h1>
<p></p>
<p></p>
<p>What is Relay?</p>
<p></p>
<p></p>
<p>Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.</p>
<p></p>
<p></p>
<p>How to use TypeScript in create-react-app application?</p>
<p></p>
<p></p>
<p>Starting from react-scripts@2.1.0 or higher, there is a built-in support for typescript. i.e, create-react-app now supports typescript natively. You can just pass --typescript option as below
<br></br>
<br></br>npx create-react-app my-app --typescript
<br></br>
<br></br># or
<br></br>
<br></br>yarn create react-app my-app --typescript
<br></br>But for lower versions of react scripts, just supply --scripts-version option as react-scripts-ts while you create a new project. react-scripts-ts is a set of adjustments to take the standard create-react-app project pipeline and bring TypeScript into the mix.
<br></br>
<br></br>Now the project layout should look like the following:
<br></br>
<br></br>my-app/
<br></br>├─ .gitignore
<br></br>├─ images.d.ts
<br></br>├─ node_modules/
<br></br>├─ public/
<br></br>├─ src/
<br></br>│ └─ ...
<br></br>├─ package.json
<br></br>├─ tsconfig.json
<br></br>├─ tsconfig.prod.json
<br></br>├─ tsconfig.test.json
<br></br>└─ tslint.json</p>
<p></p>
<p></p>
<p>What are the main features of Reselect library?</p>
<p></p>
<p></p>
<p>Let's see the main features of Reselect library,
<br></br>
<br></br>[1] Selectors can compute derived data, allowing Redux to store the minimal possible state.
<br></br>[2] Selectors are efficient. A selector is not recomputed unless one of its arguments changes.
<br></br>[3] Selectors are composable. They can be used as input to other selectors.</p>
<p></p>
<p></p>
<p>Give an example of Reselect usage?</p>
<p></p>
<p></p>
<p>Let's take calculations and different amounts of a shipment order with the simplified usage of Reselect:
<br></br>
<br></br>import { createSelector } from 'reselect'
<br></br>
<br></br>const shopItemsSelector = state => state.shop.items
<br></br>const taxPercentSelector = state => state.shop.taxPercent
<br></br>
<br></br>const subtotalSelector = createSelector(
<br></br> shopItemsSelector,
<br></br> items => items.reduce((acc, item) => acc + item.value, 0)
<br></br>)
<br></br>
<br></br>const taxSelector = createSelector(
<br></br> subtotalSelector,
<br></br> taxPercentSelector,
<br></br> (subtotal, taxPercent) => subtotal * (taxPercent / 100)
<br></br>)
<br></br>
<br></br>export const totalSelector = createSelector(
<br></br> subtotalSelector,
<br></br> taxSelector,
<br></br> (subtotal, tax) => ({ total: subtotal + tax })
<br></br>)
<br></br>
<br></br>let exampleState = {
<br></br> shop: {
<br></br> taxPercent: 8,
<br></br> items: [
<br></br> { name: 'apple', value: 1.20 },
<br></br> { name: 'orange', value: 0.95 },
<br></br> ]
<br></br> }
<br></br>}
<br></br>
<br></br>console.log(subtotalSelector(exampleState)) // 2.15
<br></br>console.log(taxSelector(exampleState)) // 0.172
<br></br>console.log(totalSelector(exampleState)) // { total: 2.322 }</p>
<p></p>
<p></p>
<p>-</p>
<p></p>
<p></p>
<p>-</p>
<p></p>
<p></p>
<p>Does the statics object work with ES6 classes in React?</p>
<p></p>
<p></p>
<p>No, statics only works with React.createClass():
<br></br>
<br></br>someComponent= React.createClass({
<br></br> statics: {
<br></br> someMethod: function() {
<br></br> // ..
<br></br> }
<br></br> }
<br></br>})
<br></br>But you can write statics inside ES6+ classes as below,
<br></br>
<br></br>class Component extends React.Component {
<br></br> static propTypes = {
<br></br> // ...
<br></br> }
<br></br>
<br></br> static someMethod() {
<br></br> // ...
<br></br> }
<br></br>}
<br></br>or writing them outside class as below,
<br></br>
<br></br>class Component extends React.Component {
<br></br> ....
<br></br>}
<br></br>
<br></br>Component.propTypes = {...}
<br></br>Component.someMethod = function(){....}</p>
<p></p>
<p></p>
<p>Can Redux only be used with React?</p>
<p></p>
<p></p>
<p>Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.</p>
<p></p>
<p></p>
<p>Do you need to have a particular build tool to use Redux?</p>
<p></p>
<p></p>
<p>Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.</p>
<p></p>
<p></p>
<p>How Redux Form initialValues get updated from state?</p>
<p></p>
<p></p>
<p>You need to add enableReinitialize : true setting.
<br></br>
<br></br>const InitializeFromStateForm = reduxForm({
<br></br> form: 'initializeFromState',
<br></br> enableReinitialize : true
<br></br>})(UserEdit)
<br></br>
<br></br>If your initialValues prop gets updated, your form will update too.</p>
<p></p>
<p></p>
<p>How React PropTypes allow different types for one prop?</p>
<p></p>
<p></p>
<p>You can use oneOfType() method of PropTypes.
<br></br>
<br></br>For example, the height property can be defined with either string or number type as below:
<br></br>
<br></br>Component.propTypes = {
<br></br> size: PropTypes.oneOfType([
<br></br> PropTypes.string,
<br></br> PropTypes.number
<br></br> ])
<br></br>}</p>
<p></p>
<p></p>
<p>Can I import an SVG file as react component?</p>
<p></p>
<p></p>
<p>You can import SVG directly as component instead of loading it as a file. This feature is available with react-scripts@2.0.0 and higher.
<br></br>
<br></br>import { ReactComponent as Logo } from './logo.svg'
<br></br>
<br></br>const App = () => (
<br></br> </p>
<div>
<br></br> {/* Logo is an actual react component */}
<br></br>
<br></br> </div>
<br></br>)
<p></p>
<p></p>
<p>Why are inline ref callbacks or functions not recommended?</p>
<p></p>
<p></p>
<p>If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.
<br></br>
<br></br>class UserForm extends Component {
<br></br> handleSubmit = () => {
<br></br> console.log("Input Value is: ", this.input.value)
<br></br> }
<br></br>
<br></br>
<br></br> render () {
<br></br> return (
<br></br>
<br></br> this.input = input} /> // Access DOM input in handle submit
<br></br> Submit
<br></br>
<br></br> )
<br></br> }
<br></br>}
<br></br>But our expectation is for the ref callback to get called once, when the component mounts. One quick fix is to use the ES7 class property syntax to define the function
<br></br>
<br></br>class UserForm extends Component {
<br></br> handleSubmit = () => {
<br></br> console.log("Input Value is: ", this.input.value)
<br></br> }
<br></br>
<br></br> setSearchInput = (input) => {
<br></br> this.input = input
<br></br> }
<br></br>
<br></br> render () {
<br></br> return (
<br></br>
<br></br> // Access DOM input in handle submit
<br></br> Submit
<br></br>
<br></br> )
<br></br> }
<br></br>}
<br></br>**Note:** In React v16.3,</p>
<p></p>
<p></p>
<p>What is render hijacking in react?</p>
<p></p>
<p></p>
<p>The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enable hijacking, but by using HOC you make your component behave differently.</p>
<p></p>
<p></p>
<p>What are HOC factory implementations?</p>
<p></p>
<p></p>
<p>There are two main ways of implementing HOCs in React.
<br></br>
<br></br>Props Proxy (PP) and
<br></br>Inheritance Inversion (II).
<br></br>But they follow different approaches for manipulating the WrappedComponent.
<br></br>
<br></br>Props Proxy
<br></br>
<br></br>In this approach, the render method of the HOC returns a React Element of the type of the WrappedComponent. We also pass through the props that the HOC receives, hence the name Props Proxy.
<br></br>
<br></br>function ppHOC(WrappedComponent) {
<br></br> return class PP extends React.Component {
<br></br> render() {
<br></br> return
<br></br> }
<br></br> }
<br></br>}
<br></br>Inheritance Inversion
<br></br>
<br></br>In this approach, the returned HOC class (Enhancer) extends the WrappedComponent. It is called Inheritance Inversion because instead of the WrappedComponent extending some Enhancer class, it is passively extended by the Enhancer. In this way the relationship between them seems inverse.
<br></br>
<br></br>function iiHOC(WrappedComponent) {
<br></br> return class Enhancer extends WrappedComponent {
<br></br> render() {
<br></br> return super.render()
<br></br> }
<br></br> }
<br></br>}</p>
<p></p>
<p></p>
<p>How to pass numbers to React component?</p>
<p></p>
<p></p>
<p>You should be passing the numbers via curly braces({}) where as strings in quotes
<br></br>
<br></br> React.render(, document.getElementById('container'));</p>
<p></p>
<p></p>
<p>Do I need to keep all my state into Redux? Should I ever use react internal state?</p>
<p></p>
<p></p>
<p>It is up to the developer's decision, i.e., it is developer's job to determine what kinds of state make up your application, and where each piece of state should live. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.
<br></br>
<br></br>Below are the thumb rules to determine what kind of data should be put into Redux
<br></br>
<br></br>[1] Do other parts of the application care about this data?
<br></br>[2] Do you need to be able to create further derived data based on this original data?
<br></br>[3] Is the same data being used to drive multiple components?
<br></br>[4] Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
<br></br>[5] Do you want to cache the data (i.e, use what's in state if it's already there instead of re-requesting it)?</p>
<p></p>
<p></p>
<p>What is the purpose of registerServiceWorker in React?</p>
<p></p>
<p></p>
<p>React creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that's what you should know about service worker for now. It's all about adding offline capabilities to your site.
<br></br>
<br></br> import React from 'react';
<br></br> import ReactDOM from 'react-dom';
<br></br> import App from './App';
<br></br> import registerServiceWorker from './registerServiceWorker';
<br></br>
<br></br> ReactDOM.render(, document.getElementById('root'));
<br></br> registerServiceWorker();</p>
<p></p>
<p></p>
<p>What is React memo function?</p>
<p></p>
<p></p>
<p>Class components can be restricted from re-rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.
<br></br>
<br></br>const MyComponent = React.memo(function MyComponent(props) {
<br></br> /* only rerenders if props change */
<br></br>});</p>
<p></p>
<p></p>
<p>What is React lazy function?</p>
<p></p>
<p></p>
<p>The React.lazy function lets you render a dynamic import as a regular component. It will automatically load the bundle containing the OtherComponent when the component gets rendered. This must return a Promise which resolves to a module with a default export containing a React component.
<br></br>
<br></br>const OtherComponent = React.lazy(() => import('./OtherComponent'));
<br></br>
<br></br>function MyComponent() {
<br></br> return (
<br></br> </p>
<div>
<br></br>
<br></br> </div>
<br></br> );
<br></br>}
<br></br>Note: React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we still recommend React Loadable.
<p></p>
<p></p>
<p>How to prevent unnecessary updates using setState?</p>
<p></p>
<p></p>
<p>You can compare the current value of the state with an existing state value and decide whether to rerender the page or not. If the values are the same then you need to return null to stop re-rendering otherwise return the latest state value.
<br></br>
<br></br>For example, the user profile information is conditionally rendered as follows,
<br></br>
<br></br>getUserProfile = user => {
<br></br> const latestAddress = user.address;
<br></br> this.setState(state => {
<br></br> if (state.address === latestAddress) {
<br></br> return null;
<br></br> } else {
<br></br> return { title: latestAddress };
<br></br> }
<br></br> });
<br></br>};</p>
<p></p>
<p></p>
<p>How do you render Array, Strings and Numbers in React 16 Version?</p>
<p></p>
<p></p>
<p>Arrays: Unlike older releases, you don't need to make sure render method return a single element in React16. You are able to return multiple sibling elements without a wrapping element by returning an array.
<br></br>
<br></br>For example, let us take the below list of developers,
<br></br>
<br></br>const ReactJSDevs = () => {
<br></br> return [
<br></br> </p>
<li>John</li>
,
<br></br> <li>Jackie</li>,
<br></br> <li>Jordan</li>
<br></br> ];
<br></br>}
<br></br>You can also merge this array of items in another array component.
<br></br>
<br></br>const JSDevs = () => {
<br></br> return (
<br></br> <ul>
<br></br> <li>Brad</li>
<br></br> <li>Brodge</li>
<br></br>
<br></br> <li>Brandon</li>
<br></br> </ul>
<br></br> );
<br></br>}
<br></br>Strings and Numbers: You can also return string and number type from the render method.
<br></br>
<br></br>render() {
<br></br> return ‘Welcome to ReactJS questions’;
<br></br>}
<br></br>// Number
<br></br>render() {
<br></br> return 2018;
<br></br>}
<p></p>
<p></p>
<p>How to use class field declarations syntax in React classes?</p>
<p></p>
<p></p>
<p>React Class Components can be made much more concise using the class field declarations. You can initialize the local state without using the constructor and declare class methods by using arrow functions without the extra need to bind them.
<br></br>
<br></br>Let's take a counter example to demonstrate class field declarations for state without using constructor and methods without binding,
<br></br>
<br></br>class Counter extends Component {
<br></br> state = { value: 0 };
<br></br>
<br></br> handleIncrement = () => {
<br></br> this.setState(prevState => ({
<br></br> value: prevState.value + 1
<br></br> }));
<br></br> };
<br></br>
<br></br> handleDecrement = () => {
<br></br> this.setState(prevState => ({
<br></br> value: prevState.value - 1
<br></br> }));
<br></br> };
<br></br>
<br></br> render() {
<br></br> return (
<br></br> </p>
<div>
<br></br> {this.state.value}
<br></br>
<br></br> +
<br></br> -
<br></br> </div>
<br></br> )
<br></br> }
<br></br>}
<p></p>
<p></p>
<p>What are hooks?</p>
<p></p>
<p></p>
<p>Hooks is a new feature(React 16.8) that lets you use state and other React features without writing a class.
<br></br>
<br></br>Let's see an example of useState hook:
<br></br>
<br></br>import { useState } from 'react';
<br></br>
<br></br>function Example() {
<br></br> // Declare a new state variable, which we'll call "count"
<br></br> const [count, setCount] = useState(0);
<br></br>
<br></br> return (
<br></br> </p>
<div>
<br></br> <p>You clicked {count} times</p>
<br></br> setCount(count + 1)}>
<br></br> Click me
<br></br>
<br></br> </div>
<br></br> );
<br></br>}
<p></p>
<p></p>
<p>What rules need to be followed for hooks?</p>
<p></p>
<p></p>
<p>You need to follow two rules in order to use hooks,
<br></br>
<br></br>[1] Call Hooks only at the top level of your react functions. i.e, You shouldn’t call Hooks inside loops, conditions, or nested functions. This will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between multiple useState and useEffect calls.
<br></br>
<br></br>[2] Call Hooks from React Functions only. i.e, You shouldn’t call Hooks from regular JavaScript functions.</p>
<p></p>
<p></p>
<p>How to ensure hooks followed the rules in your project?</p>
<p></p>
<p></p>
<p>React team released an ESLint plugin called eslint-plugin-react-hooks that enforces these two rules. You can add this plugin to your project using the below command,
<br></br>
<br></br>npm install eslint-plugin-react-hooks@next
<br></br>
<br></br>And apply the below config in your ESLint config file,
<br></br>// Your ESLint configuration
<br></br>{
<br></br> "plugins": [
<br></br> // ...
<br></br> "react-hooks"
<br></br> ],
<br></br> "rules": {
<br></br> // ...
<br></br> "react-hooks/rules-of-hooks": "error"
<br></br> }
<br></br>}
<br></br>
<br></br>Note: This plugin is intended to use in Create React App by default.</p>
<p></p>
<p></p>
<p>What are the differences between Flux and Redux?</p>
<p></p>
<p></p>
<p>Below are the major differences between Flux and Redux</p>
<p></p>
<p>What are the benefits of React Router V4?</p>
<p></p>
<p>Below are the main benefits of React Router V4 module,
<br></br>
<br></br>In React Router v4(version 4), the API is completely about components. A router can be visualized as a single component() which wraps specific child router components().
<br></br>You don't need to manually set history. The router module will take care history by wrapping routes with component.
<br></br>The application size is reduced by adding only the specific router module(Web, core, or native)</p>
<p></p>
<p>Can you describe about componentDidCatch lifecycle method signature?</p>
<p></p>
<p>The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters,
<br></br>
<br></br>[1] error: - The error object which was thrown
<br></br>[2] info: - An object with a componentStack key contains the information about which component threw the error.
<br></br>The method structure would be as follows
<br></br>
<br></br>componentDidCatch(error, info)</p>
<p></p>
<p>In which scenarios error boundaries do not catch errors?</p>
<p></p>
<p>Below are the cases in which error boundaries doesn't work,
<br></br>
<br></br>[1] Inside Event handlers
<br></br>[2] Asynchronous code using setTimeout or requestAnimationFrame callbacks
<br></br>[3] During Server side rendering
<br></br>[4] When errors thrown in the error boundary code itself</p>
<p></p>
<p>Why do you not need error boundaries for event handlers?</p>
<p></p>
<p>Error boundaries do not catch errors inside event handlers.
<br></br>
<br></br>React doesn’t need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don’t happen during rendering. So if they throw, React still knows what to display on the screen.
<br></br>
<br></br>If you need to catch an error inside an event handler, use the regular JavaScript try / catch statement:
<br></br>
<br></br>class MyComponent extends React.Component {
<br></br> constructor(props) {
<br></br> super(props);
<br></br> this.state = { error: null };
<br></br> this.handleClick = this.handleClick.bind(this);
<br></br> }
<br></br>
<br></br> handleClick() {
<br></br> try {
<br></br> // Do something that could throw
<br></br> } catch (error) {
<br></br> this.setState({ error });
<br></br> }
<br></br> }
<br></br>
<br></br> render() {
<br></br> if (this.state.error) {
<br></br> return </p>
<h1>Caught an error.</h1>
<br></br> }
<br></br> return Click Me
<br></br> }
<br></br>}
<br></br>Note that the above example is demonstrating regular JavaScript behavior and doesn’t use error boundaries.
<p></p>
<p>What is the difference between try catch block and error boundaries?</p>
<p></p>
<p>Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen.
<br></br>
<br></br>For example, the try catch block used for below imperative code
<br></br>
<br></br>try {
<br></br> showButton();
<br></br>} catch (error) {
<br></br> // ...
<br></br>}
<br></br>Whereas error boundaries wrap declarative code as below,
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.</p>
<p></p>
<p>What is the behavior of uncaught errors in react 16?</p>
<p></p>
<p>In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.</p>
<p></p>
<p>What is the proper placement for error boundaries?</p>
<p></p>
<p>The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches,
<br></br>
<br></br>[1] You can wrap top-level route components to display a generic error message for the entire application.
<br></br>
<br></br>[2] You can also wrap individual components in an error boundary to protect them from crashing the rest of the application.</p>
<p></p>
<p>What is the benefit of component stack trace from error boundary?</p>
<p></p>
<p>Apart from error messages and javascript stack, React16 will display the component stack trace with file names and line numbers using error boundary concept.
<br></br>
<br></br>For example, BuggyCounter component displays the component stack trace as below,</p>
<p>What is the required method to be defined for a class component?</p>
<p>The render() method is the only required method in a class component. i.e, All methods other than render method are optional for a class component.</p>
<p>What are the possible return types of render method?</p>
<p>Below are the list of following types used and return from render method,
<br></br>
<br></br>[1] React elements: Elements that instruct React to render a DOM node. It includes html elements such as </p>
<div></div>
and user defined elements.
<br></br>
<br></br>[2] Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements
<br></br>
<br></br>[3] Portals: Render children into a different DOM subtree.
<br></br>
<br></br>[4] String and numbers: Render both Strings and Numbers as text nodes in the DOM
<br></br>
<br></br>[5] Booleans or null: Doesn’t render anything but these types are used to conditionally render content.
<p>What is the main purpose of constructor?</p>
<p>The constructor is mainly used for two purposes,
<br></br>
<br></br>[1] To initialize local state by assigning object to this.state
<br></br>[2] For binding event handler methods to the instance For example, the below code covers both the above cases,
<br></br>constructor(props) {
<br></br> super(props);
<br></br> // Don't call this.setState() here!
<br></br> this.state = { counter: 0 };
<br></br> this.handleClick = this.handleClick.bind(this);
<br></br>}</p>