Intro Flashcards

1
Q

How does React work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Context?

A

Context provides a way to pass data through the component tree without having to pass props down manually at every level. Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. Using context, we can avoid passing props through intermediate elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is props in React?

A

Props are inputs to a React component. They are single values or objects containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. i.e, 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 React 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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the use of refs?

A

Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component.

Refs provide a way to access DOM nodes or React elements created in the render method. They should be avoided in most cases, however, they can be useful when we need direct access to DOM element or an instance of a component.

There are a few good use cases for refs:
Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries.

Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();  }
  render() {
    return <div>;  }
}</div>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Jest

A

Jest is a JavaScript unit testing framework made by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It’s often used for testing React components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the advantages of ReactJS?

A

Increases the application’s performance with Virtual DOM
JSX makes code is easy to read and write
It renders both on client and server side
Easy to write UI Test cases and integration with tools such as JEST.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the major features of ReactJS?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the differences between a class component and functional component?

A
Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.
Class components extend from React.Component.
In here you have to use this keyword to access the props and functions that you declare inside the class components.

Functional Components

Functional Components are simpler comparing to class-based functions.
Functional Components mainly focuses on the UI of the application, not on the behavior.
To be more precise these are basically render function in the class component.
Functional Components can have state and mimic lifecycle events using Reach Hooks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Where in a React component should you make an AJAX request?

A

componentDidMount is where an AJAX request should be made in a React component.
This method will be executed when the component “mounts” (is added to the DOM) for the first time. This method is only executed once during the component’s life. Importantly, you can’t guarantee the AJAX request will have resolved before the component mounts. If it doesn’t, that would mean that you’d be trying to setState on an unmounted component, which would not work. Making your AJAX request in componentDidMount will guarantee that there’s a component to update.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between state and props?

A

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. They are received from above 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What’s the difference between a Controlled component and an Uncontrolled one in React?

A

This relates to stateful DOM components (form elements) and the React docs explain the difference:

A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange. A parent component “controls” it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a “dumb component”.

A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does it mean for a component to be mounted in React?

A

It has a corresponding element created in the DOM and is connected to that.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are Fragments?

A

It’s common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

When rendering a list what is a key and what is it’s purpose?

A

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.

*Most often you would use IDs from your data as keys. When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort. It is not recommend to use indexes for keys if the items can reorder, as that would be slow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

React Hooks: What is useState() in React?

A


const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(…);

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};
useState is one of build-in react hooks. useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state.
We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are stateful components?

A

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These Stateful components are always class components and have a state that gets initialized in the constructor.

class App extends Component {
 constructor(props) {
  super(props);
  this.state = { count: 0 };
 }
 render() {
    // omitted for brevity
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How would you prevent a component from rendering in React?

A

Return null from the render method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are Stateless components?

A

If the behaviour is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for stateless functional components.

There are a lot of benefits if you decide to use stateless functional components here; they are:

easy to write, understand, and test, and

you can avoid the this keyword altogether.

Stateful/Container/Smart component:
class Main extends Component {
 constructor() {
   super()
   this.state = {
     books: []
   }
 }
 render() {

}
}

Stateless/Presentational/Dumb component:

const BooksList = ({books}) => {
 return (
   <ul>
     {books.map(book => {
       return <li>book</li>
     })}
   </ul>
 )
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are portals in React and when do we need them?

A

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

Sometimes it’s useful to insert a child into a different location in the DOM:

20
Q

How to pass a parameter to an event handler or callback?

A

You can use an arrow function to wrap around an event handler and pass parameters:
this.handleClick(id)} />

21
Q

What happens during the lifecycle of a React component?

A

At the highest level, React components have lifecycle events that fall into three general categories:
Initialization
State/Property Updates
Destruction

  1. INTIALIZATION
    getInitialState()
    getDefaultProps()

componentWillMount()
render()
componentDidMount()

  1. UPDATE
    componentWillReceiveProps()
    shouldComponentUpdate()

componentWillMount()
render()
componentDidUpdate()

3.DESTRUCTION
componentWillUnmount()

22
Q

What is the difference between Component and Container in Redux?

A
omponent is part of the React API. A Component is a class or function that describes part of a React UI.
Container is an informal term for a React component that is connected to a redux store. Containers receive Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.
23
Q

How do you prevent the default behavior in an event callback in React?

A

You call e.preventDefault(); on the event e passed into the callback.

24
Q

What is the purpose of using super constructor with props argument?

A

A child class constructor cannot make use of this reference until super() method has been called. The same applies for ES6 sub-classes as well. The main reason of passing props parameter to super() call is to access this.props in your child constructors.

25
Q

What happens when you call setState? (what’s happening in the background)

A

The first thing React will do when setState is called is merge the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.
To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree.
By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.

26
Q

What are Higher-Order components?

A

A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature We call them as “pure’ components” because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. Concretely, a higher-order component is a function that takes a component and returns a new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

HOC can be used for many use cases as below,

Code reuse, logic and bootstrap abstraction

State abstraction and manipulation

Props manipulation

27
Q

What is {this.props.children} and when you should use it?

A

Some components don’t know their children ahead of time. This is especially common for components like Sidebar or Dialog that represent generic “boxes”.

28
Q

what is a store in redux

A

A store is an immutable object tree in Redux. A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer. Let us see how we can create a store using the createStore method from Redux.

A store holds the whole state tree of your application. The only way to change the state inside it is to dispatch an action on it.

29
Q

What’s the typical flow of data like in a React + Redux

A

Redux follows the unidirectional data flow. It means that your application data will follow in one-way binding data flow.

As the application grows & becomes complex, it is hard to reproduce issues and add new features if you have no control over the state of your application.

30
Q

The best way to bind event handlers in React

A

With ES7 class properties (currently supported with Babel), we can do bindings at the method definition:

class HelloWorld extends Component {  
    handleClick = (event) => {    
        console.log(this.state.name);  
    }  
    render() {    
       return ()  
   } 
}

Use Arrow Function binding whenever possible
If you must generate bindings dynamically, consider caching the handlers if the bindings become a performance issue

31
Q

What is prop drilling and how can you avoid it?

A

The problem with Prop Drilling is that whenever data from the Parent component will be needed, it would have to come from each level, Regardless of the fact that it is not needed there and simply needed in last.

A better alternative to this is using useContext hook. The useContext hook is based on Context API and works on the mechanism of Provider and Consumer. Provider needs to wrap components inside Provider Components in which data have to be consumed. Then in those components, using the useContext hook that data needs to be consumed.

32
Q

What is the point of shouldComponentUpdate() method?

A

The shouldComponentUpdate method allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. It only updates the component if the props passed to it changes.

33
Q

What are forward refs?

A

React forwardRef is a method that allows parent components pass down (i.e., “forward”) refs to their children. Using forwardRef in React gives the child component a reference to a DOM element created by its parent component. This then allows the child to read and modify that element anywhere it is being used.

We can achieve this by using refs. With refs, we have access to a DOM node that is represented by an element. As a result, we can modify it without touching its state or re-rendering it.

Because refs hold a reference to the DOM element itself, we can manipulate it with native JavaScript functions that are unavailable in the React library. For instance, we can initiate focus on input field when a button is clicked:

import * as React from “react”;
import ReactDOM from “react-dom”;

export default function App() {
 const ref = React.useRef();
 function focus() {
   ref.current.focus();
 }

return (

<div>

Focus
</div>

);
}

NOT RECOMMENDED BUT POSSIBLE TO DO THIS BY JS

33
Q

What are forward refs?

A

React forwardRef is a method that allows parent components pass down (i.e., “forward”) refs to their children. Using forwardRef in React gives the child component a reference to a DOM element created by its parent component. This then allows the child to read and modify that element anywhere it is being used.

We can achieve this by using refs. With refs, we have access to a DOM node that is represented by an element. As a result, we can modify it without touching its state or re-rendering it.

Because refs hold a reference to the DOM element itself, we can manipulate it with native JavaScript functions that are unavailable in the React library. For instance, we can initiate focus on input field when a button is clicked:

import * as React from “react”;
import ReactDOM from “react-dom”;

export default function App() {
 const ref = React.useRef();
 function focus() {
   ref.current.focus();
 }

return (

<div>

Focus
</div>

);
}

NOT RECOMMENDED BUT POSSIBLE TO DO THIS BY JS

34
Q

What are typical middleware choices for handling asynchronous calls in Redux?\

A

By default, Redux’s actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.

There are two very popular middleware libraries that allow for side effects and asynchronous actions: Redux Thunk and Redux Saga. In this post, you will explore Redux Thunk.

Thunk is a programming concept where a function is used to delay the evaluation/calculation of an operation.

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.

35
Q

What is the difference between ShadowDOM and VirtualDOM?

A

In Virtual DOM concept copy of DOM is saved in the memory and while any change is done in the DOM, it’s compared to find differences. Then browser knows which elements were changed and can update only those part of the application to avoid re-rendering all the DOM. It’s done to improve the performance of the UI libraries.

Virtual DOM is creating a copy of the whole DOM object, and Shadow DOM creates small pieces of the DOM object which has their own, isolated scope for the element they represent.

36
Q

Why do we need to bind methods inside our class component’s constructor?

A

This is because whenever inside a class component when we need to pass a function as props to the child component, we have to do one of the following:

Bind it inside the constructor function.
Bind it inline (which can have some performance issues).
Use arrow function (which is the same as property initializer syntax).

When we use an arrow function inside our class (using property initializer feature), it becomes the method property of the instance. As this will always be determined by the outer scope, it will point to the instance of the class. Let’s see that in action:

https://dev.to/aman_singh/why-do-we-need-to-bind-methods-inside-our-class-component-s-constructor-45bn#:~:text=This%20is%20because%20whenever%20inside,same%20as%20property%20initializer%20syntax).

37
Q

What are stateless components

A

Stateless components are those components which don’t have any state at all, which means you can’t use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

38
Q

What are react hooks

A

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. … You can also create your own Hooks to reuse stateful behavior between different components.

39
Q

What is Lifting State Up in ReactJS?

A

In React, sharing state is accomplished by moving it up to the closest common ancestor of the components that need it. This is called “lifting state up”. We will remove the local state from the TemperatureInput and move it into the Calculator instead.

40
Q

What’s the difference between useRef and createRef?

A

The difference is that createRef will always create a new ref. In a class-based component, you would typically put the ref in an instance property during construction (e.g. this.input = createRef()). You don’t have this option in a function component. useRef takes care of returning the same ref each time as on the initial rendering.

41
Q

What would be the common mistake of function being called every time the component renders?

A

You need to make sure that function is not being called while passing the function as a parameter.

42
Q

What are error boundaries in ReactJS (16)?

A

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

42
Q

What are error boundaries in ReactJS (16)?

A

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

43
Q

What is a reducer?

A

In Redux, a reducer is a PURE FUNCTION that takes an action and the previous state of the application and returns the new state. The action describes what happened and it is the reducer’s job to return the new state based on that action.

44
Q

Can you force a React component to rerender without calling setState

A

Disclaimer: NOT AN ANSWER TO THE PROBLEM.

Leaving an Important note here:

If you are trying to forceupdate a stateless component, chances are there is something wrong with your design.

45
Q

Why does React use SyntheticEvents?

A

Once click on a div happens, React’s listener on document node finds your event listener and calls it with SyntheticEvent. This way, react doesn’t have to re-create and clear listeners from DOM all the time, it just changes it’s internal listener registry