React Flashcards

1
Q
  1. What is React?
A

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 of 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
2
Q
  1. What is JSX?
A

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.

JSX Code:

const App = () => {
    return <div>Hello world!</div>
}
Equivalent JS Code:
const App = () => {
  return React.createElement("div", null, "Hello world!");
};

JS is standard javascript, JSX is an HTML-like syntax that you can use with React to (theoretically) make it easier and more intuitive to create React components. As the docs say, the only purpose is to make it easier to create React components… there’s not much else there. Without JSX, creating large, nested HTML documents using JS syntax would be a large pain in the rear; JSX simply makes that process easier.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. What is the difference between Element and Component?
A

A React Component is a template. A blueprint. A global definition. This can be either a function or a class (with a render function).

A React Element is what gets returned from components. It’s an object that virtually describes the DOM nodes that a component represents. With a function component, this element is the object that the function returns. With a class component, the element is the object that the component’s render function returns. React elements are not what we see in the browser.

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to create components in React?

When to use a Class Component over a Function Component?

A

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:

const FunctionalComponent = () => {
 return h1 Hello, world /h1 ;
};
function FunctionalComponent() {
 return  h1 Hello, world /h1 ;
}
Class Components: You can also use ES6 class to define a component. The above function component can be written as:

import React, { Component } from “react”;

class ClassComponent extends Component {
 render() {
   return  h1 Hello, world /h1 ;
 }
}
without using destructuring

import React from “react”;

class ClassComponent extends React.Component {
 render() {
   return  h1 Hello, world /h1 ;
 }
}

If the component needs state or lifecycle methods then use class component otherwise use function component. However, from React 16.8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component.

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

What are Pure Components? In class and in funcitonal.

A

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.

https://www.freecodecamp.org/news/react-shouldcomponentupdate-demystified-c5d323099ef6/

Reconciliation in the context of React means to make React’s virtual DOM tree consistent with the real DOM tree of your browser. This happens during (re-)rendering

To avoid unnecessary renders, thus reconciliation, we can use PureComponent (with class components) or React.memo() (with function components).

In PureComponent every time props or state changes, React performs a shallow compare between props and nextProps objects, and also between state and nextState objects.

React.memo() does the same as PureComponent but it does not check for changes in state, only in props.

Use pure components responsibly. The shallow comparison does not come for free. It’s an expensive computation and it’s better to avoid it if not necessary.
Don’t convert every component to pure, it could end up in worse performance.
Start instead by trying to convert a component to pure if it renders a lot of unnecessary times.
If you are not familiar with pure components, the advice is to only rely on them if you face some performance issues.

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

What is state in React?

A

What is State? The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component.

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.

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

What are props in React?

A

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

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

What is the difference between state and props?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
  1. Why should we not update the state directly?
A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the purpose of callback function as an argument of setState()?

A

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’))

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

What is the difference between HTML and React event handling?

A

Below are some of the main differences 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.')
}
In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer "activateLasers" function in the first point for example)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
  1. How to bind methods or event handlers in JSX callbacks in class?
A

https://reactjs.org/docs/handling-events.html

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

read here

https://stackoverflow.com/questions/53215067/how-can-i-bind-function-with-hooks-in-react

There’s no need to bind functions/callbacks in functional components since there’s no this in functions. In classes, it was important to bind this because we want to ensure that the this in the callbacks referred to the component’s instance itself. However, doing .bind in the constructor has another useful property of creating the functions once during the entire lifecycle of the component and a new callback wasn’t created in every call of render(). To do only initialize the callback once using React hooks, you would use useCallback.

Classes
class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

handleClick() {
console.log(‘Click happened’);
}

  render() {
    return Click Me;
  }
}
Hooks
function Foo() {
  const memoizedHandleClick = useCallback(
    () => {
      console.log('Click happened');
    },
    [], // Tells React to memoize regardless of arguments.
  );
  return Click Me;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
  1. How to pass a parameter to an event handler or callback?
A

https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method

Easy Way
Use an arrow function:

return (
this.handleSort(column)}>{column}
);
This will create a new function that calls handleSort with the right params.

Better Way
Extract it into a sub-component. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.

If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):

Sub-component

class TableHeader extends Component {
  handleClick = () => {
    this.props.onHeaderClick(this.props.value);
  }

render() {
return (

    {this.props.column}

);   } } Main component

{this.props.defaultColumns.map((column) => (

))}
Old Easy Way (ES5)

Use .bind to pass the parameter you want, this way you are binding the function with the Component context :

return (
{column}
);

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

What are synthetic events in React?

A

SyntheticEvent is a cross-browser wrapper around the browser’s native event. It’s API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

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

What are inline conditional expressions?

A

You can use either if statements or ternary expressions which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.

<h1>Hello!</h1>
{
    messages.length > 0 && !isLogin?
      <h2>
          You have {messages.length} unread messages.
      </h2>
      :
      <h2>
          You don't have unread messages.
      </h2>
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is “key” prop and what is the benefit of using it in arrays of elements?

A

A key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.

Most often we use ID from our data as key:

const todoItems = todos.map((todo) =>
  <li>
    {todo.text}
  </li>
)
When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
  <li>
    {todo.text}
  </li>
)
Note:

Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
If you extract list item as separate component then apply keys on list component instead of li tag.
There will be a warning message in the console if the key prop is not present on list items.

17
Q

What is the use of refs?

A

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.

18
Q

How to create refs?

A

There are two approaches

This is a recently added approach. Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property within constructor.

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }
  render() {
    return <div></div>
  }
}
You can also use ref callbacks approach regardless of React version. For example, the search bar component's input element accessed as follows,
class SearchBar extends Component {
   constructor(props) {
      super(props);
      this.txtSearch = null;
      this.state = { term: '' };
      this.setInputSearchRef = e => {
         this.txtSearch = e;
      }
   }
   onInputChange(event) {
      this.setState({ term: this.txtSearch.value });
   }
   render() {
      return (
  );    } } You can also use refs in function components using closures. Note: You can also use inline ref callbacks even though it is not a recommended approach
19
Q

What are forward refs?

A

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

const ButtonElement = React.forwardRef((props, ref) => (

{props.children}

));

// Create ref to the DOM button:
const ref = React.createRef();
{'Forward Ref'}
20
Q

Which is preferred option with in callback refs and findDOMNode()?

A

It is preferred to use callback refs over findDOMNode() API. Because findDOMNode() prevents certain improvements in React in the future.

The legacy approach of using findDOMNode:

class MyComponent extends Component {
  componentDidMount() {
    findDOMNode(this).scrollIntoView()
  }
  render() {
    return <div></div>
  }
}
The recommended approach is:
class MyComponent extends Component {
  constructor(props){
    super(props);
    this.node = createRef();
  }
  componentDidMount() {
    this.node.current.scrollIntoView();
  }

render() {
return <div></div>
}
}

21
Q

create 20 more cards from the list

A

starting question 23

https://github.com/sudheerj/reactjs-interview-questions#what-is-react

22
Q

React SSR frameworks

A

Getting started without frameworks is possible, but I wouldn’t recommend this approach since there are many considerations and moving parts in a React SSR app. For example, you have to handle bundling, minification, and hot reload (and more) all on your own.

gatsby

there are also things like

next
nuxt
razzle

23
Q

useState and useReducer

write increment decrement in both

A
Both of these hooks are released with the same version. useState is used to manage the state of the component. useReducer does the same thing but preferable used to when there is a complex state logic that may involve sub-values or depends on previous state.
Here are examples from the React documentation. As you can see, the same simple thing can be done with both but useReducer has more setup required. In return, it provides more information to be accessible.
useState
function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
       setCount(initialCount)}>Reset
       setCount(prevCount => prevCount - 1)}>-
       setCount(prevCount => prevCount + 1)}>+
    >
  );
}
useReducer
const initialState = {count: 0};
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}
function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
       dispatch({type: 'decrement'})}>-
       dispatch({type: 'increment'})}>+
    >
  );
}
24
Q

useState vs setState

A

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

setState is merging the previous state with the new one, it means that you dont have to pass the full state object every time you want to change some part of the state. React will update given properties and won’t touch the rest. The useState’s updater rewrites a previous state with a new one and it does not perform any merging. Its just replacement instead of merging.