Skip to content

Instantly share code, notes, and snippets.

@georgebullock
Last active April 19, 2020 13:46
Show Gist options
  • Save georgebullock/944a16795d84775a8940aef3e981882a to your computer and use it in GitHub Desktop.
Save georgebullock/944a16795d84775a8940aef3e981882a to your computer and use it in GitHub Desktop.
React Interview Questions

REACT INTERVIEW QUESTIONS

1 What is React?

React is JavaScript library that makes it easy develop UI

2 What are the major features of React?

  • Virtual DOM
  • Templating via JSX
  • Data handling via props
  • State management via state
  • Event handling via props
  • "Container" components that solve a variety of problems (e.g. Suspense for lazy loading)

3 What is JSX?

JSX is React's templating language. It resembles HTML, but it's really only syntactic sugar for React.createComponent

4 What is the difference between Element and Component?

Elements are the React's basic building blocks (e.g. a div created via JSX). Component's are organized groups of elements that are enhanced via props, state, and other components.

5 How to create components in React?

You can create components using JavaScripts default function syntax or you can use class syntax.

6 When to use a Class Component over a Function Component?

Historically you would use function components for so-called "stateless" components and class components if a component needed state. However with the addition of the "Hooks" API, you can use state with function components.

7 What are Pure Components?

Pure components don't have side effects. That means they don't mutate their props. For a given set of props, a pure component will always return the same result.

8 What is state in React?

state is a special object in React. It's private property on React components and it's used to store data that changes based events, which could be anything from a user typing something into a form to the result of a network request.

9 What are props in React?

props is special in React. It's not property on React components. It's not private. As a result it's the primary way that React components communicate with each other. Parents pass props to children. Children pass data to their parents via callbacks. That's canonical way communication in React.

10 What is the difference between state and props?

state is private to the component. props arent

11 Why should we not update the state directly?

Because state changes might be made asynchronously

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

React batches changes and they might be rendered async. That means you can't rely on the current value of state to calculate the next state. Using a callback in setState is way to ensure that this.state is what you think its going to be when you call this.setState()

13 What is the difference between HTML and React event handling?

In HTML events are handled by attaching "event listeners" to DOM nodes.

In React events are handled by passing callbacks as props to React elements.

14 How to bind methods or event handlers in JSX callbacks?

If you're using class properties then you don't need to bind your methods. You can use arrow functions to bind functions expressions directly to the class.

const handleClick = () => {}

If you're not using class properties, then you have to bind your methods in the classes constructor:

// Inside the constructor method
this.handleClick = this.handleClick.bind(this)

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

You create the parameter for the event handler or callback when you declare them. When you call the function, you can pass whatever you want to the parameter:

// Event handler with `value` as its parameter declared in a parent component
handleChange = value => this.setState({value})
// Event handler on a deeply nested component. We can pass any of the components props to the `value` parameter to relay that information to the parent.
handleChange = e => {
    const value = e.target.value
    this.props.onGreatGrandChildChange(value)
  }

16 What are synthetic events in React?

React provides a SyntheticEvent object that has the same specification as the native EventObject. As a result, you can create an event handler in React, it automatically receive the SyntheticEvent object and you can access properties like target preventDefault and stopPropagation.

17 What is inline conditional expressions?

Inline conditional expressions refers to two methods that for using conditional logic inside JSX expressions.

You can either use the ternary operator or you can use the following patterns:

// If `true`, then render expression
{true && expression}

// If `false`, then ignore expression
{false && expression}

In the context of conditional rendering expression is typically either a string, React element, or React component.

18 What are "key" props and what is the benefit of using them in arrays of elements?

Key props are a special prop that React uses to keep track of changes to arrays of React components / elements.

It's required to add the key prop to each component / element when mapping over arrays of them.

19 What is the use of refs?

Refs allow you to give your components direct access to individual DOM nodes.

20 How to create refs?

// Basic ref example
class App extends React.Component {
  ref = React.createRef();

  // Init your refs via componentDidMount
  componentDidMount() {
    console.log("this.ref: ", this.ref);
    console.log("this.ref: ", this.ref.current);
  }

  // You can also access nodes via the synthetic event object
  logNode(e) {
    console.log("this.logNode: ", e.target);
  }

  render() {
    return (
      <button onClick={this.logNode} ref={this.ref}>
        Click Me
      </button>
    );
  }
}

export default App;

21 What are forward refs?

Forward refs are components created via React.forwardRef(). React.forwardRef() props and a ref as parameters and return React nodes with ref attributes that get passed along to components lower in the React tree.

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

Don't understand the question. Not high value. Skip.

23 Why are String Refs legacy?

It's not important. Skip.

24 What is Virtual DOM?

The Virtual DOM is a virtual representation of the Real DOM.

React uses the Virtual DOM and a reconiliation (i.e. diffing) algorithm to more efficiently update the Real DOM.

25 How Virtual DOM works?

On intital load, React creates the Virtual DOM, stores it in memory, and renders the Real DOM. On application state changes React creates a new version of the Virtual DOM and compares it with the Virtual DOM stored in memory. If there are any differences between the nodes in the Virtual DOMs, React updates or removes those nodes in the Real DOM.

26 What is the difference between Shadow DOM and Virtual DOM?

The Virtual DOM is a representation of the Real DOM that SPA libraries use to more efficiently update the Real DOM.

The Shadow DOM is part of the browser that is used by web components to make their DOM representations private (i.e. they're not accessible via the document).

27 What is React Fiber?

Reacts new reconiliation algorithm released with React 16.

28 What is the main goal of React Fiber?

To make the diffing algorithm more faster and more flexible. It's headline feature is "incremental rendering", which means React will batch renders into chucks to increase rendering speed.

29 What are controlled components?

Controlled componenets are components whose props are completely controlled by its parent.

30 What are uncontrolled components?

Uncontrolled components are components that have their own state or they receive their props some external source, like an input field in the Real DOM.

31 What is the difference between createElement and cloneElement?

32 What is Lifting State Up in React?

Lifting up state refers to a step in the process of building a React app. When more than one component use the same state, you should "lift state up", which means find a common ancestor where state can live for both components or, if there is no common ancestor, create component specifically to hold state for both components.

33 What are the different phases of component lifecycle?

Render and Commit. The render phase is pure and is not allowed to have side effects. The commit phase is not pure and side effects are allowed.

34 What are the lifecycle methods of React?

The main lifecyle methods are:

  • render()
  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()
  • static getDerivedStateFromError()
  • componentDidCatch()

35 What are Higher-Order components?

HOCs are components that take components as props and return a new component without changing the component its passed as props.

The key point is they don't change (i.e. mutate) their arguments. They create something new from their arguments and return the new thing.

36 How to create props proxy for HOC component?

37 What is context?

Context is a React feature that allows you to bypass the standard parent to nested child data flow and broadcast data directly to nested components.

38 What is children prop?

The children prop is a special prop that tells React to render a component and it's children (if any).

You can think of the children prop as a placeholder for content. It's similar to the {{yield}} statement in Handlebars.

props.children can be a string, a React element, a React component, or an array of any of the above.

39 How to write comments in React?

JSX comment can written using the following syntax

{/* This is a comment */}

{/* 
	This is a multi-line 
	comment block
*/}

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

Calling super(props) executes the base classes constructor, which allows tge base class to initialize any properties that instances of the base will inherit (via protoype inheritance).

Other Fun Facts:

  • You can’t use this in a constructor until after you've called base classes constructor. That means until you call super(props) the this keyword is not available inside your React components.

  • If you try to access properties of a base class before calling super(props), thet will be undefined because if the base's constructor has not been call, then the the properties won't exist yet.

41 What is reconciliation?

Reconciliation refers to the algorithm React uses to identify differences between copies of the Virtual DOM so that it can efficiently update the Real DOM.

42 How to set state with a dynamic key name?

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

44 Is lazy function supports named exports??

React.lazy() requires that modules are dynamically loaded and the dynamically loaded modules must resolve to default-exported React component.

45 Why React uses className over class attribute?

First, because class is reserved word in JavaScript. Second, because the React team decided the convention for JSX attributes should be camel case.

46 What are fragments?

Fragments allow you to render groups of related elements/components without wrapping them in an additional container

47 Why fragments are better than container divs?

Fragments can render more semantic markup. For example, one can avoid rendering a group of table rows without having to wrap them in a container div.

48 What are portals in React?

Portals allow you to render components outside the context of their parent components. You can open a portal to different part of the document and render something.

They are useful in for things like modals.

49 What are stateless components?

Stateless components don't use a state object. Instead they receive props from their parents.

50 What are stateful components?

Stateful components use the state object and rerender on changes to state

51 How to apply validation on props in React?

You can use prop-types, flow-type, or typescript

52 What are the advantages of React?

  1. React core library is small and easy to learn
  2. React only handles the view layer, so you can orchestrate other concerns to suit your needs
  3. Virtual DOM and Reconciliation can increase site peformance
  4. React can be rendered server side to play nice with SEO

53 What are the limitations of React?

  1. React only covers the view layer. You're on your own in terms of routing, advanced state management, network requests, etc.
  2. Server-Side rendering is possible but it's hard to make work
  3. Learning React requires learning the React ecosystem, which is vast
  4. May be harder to implement certain features, like animations
  5. Configuring a React app can be a nightmare

54 What are error boundaries in React v16

Error Boundaries are container components provided by React to catch errors inside the Error Boundaries nested React tree.

55 How error boundaries handled in React v15?

Not important. Skip.

56 What are the recommended ways for static type checking?

Use a static type checker. The most popular options are TypeScript and Flow

57 What is the use of react-dom package?

ReactDOM is a library of methods that allows you to interact with the Real DOM. It's most popular method is render(), which is used as the entry point for React applications. Other methods exist that solve other problems e.g. hydrate() is used for SSR and portal() is used as an escape hatch to append components outside the main React tree.

58 What is the purpose of render method of react-dom?

It's main purpose is to render (and update) React apps. You pass a React component and a reference to a HTML element to render() and React returns a React tree and a reference to the component. Ther reference is the component for stateful components and null for stateless components.

59 What is ReactDOMServer?

60 How to use InnerHtml in React?

61 How to use styles in React?

There are several ways to apply styles in React. You can:

  1. Apply them inline via the styles prop passing your styles via an object
  2. Use external stylesheets (i.e. the traditional method)
  3. Use CSS modules, which allows you to scope your css to specific files
  4. CSS in JS libraries which allow you scope your css to components via JavaScript modules

62 How events are different in React?

63 What will happen if you use setState in constructor?

If the the component hasn't been mounted yet, you will get an error that you can't call setState on an unmounted component.

If the component has been mounted, then you will end up rendering your components twice, once from setState() and once again from 'render()'.

64 What is the impact of indexes as keys?

65 Is it good to use setState() in componentWillMount() method?

No. componentWillMount() is called before removing a component from the React tree. Calling setState() makes no sense because the changes will be destroyed when the component unmounts.

66 What will happen if you use props in initial state?

This effectively hard codes the state. When React rerenders the changes for hard coded props won't be updated. Use this.props.propName.

67 How do you conditionally render components?

There are several way to conditionally render React components. Some of the more common methods:

  1. Using if ... then logic outside of JSX
  2. Using the ternary operator inside JSX
  3. Create some rendering logic the is driven by state changes

68 Why we need to be careful when spreading props on DOM elements??

69 How you use decorators in React?

70 How do you memoize a component?

71 How you implement Server-Side Rendering or SSR?

72 How to enable production mode in React?

73 What is CRA and its benefits?

CRA is boilerplate config that allows you to use React without less responsibility for configuration.

It's a good option for more generic projects that don't have special configuration requirements. In those cases, you can start coding your app much faster and avoid the buring time on basic configuration.

74 What is the lifecycle methods order in mounting?

*Bold items are considered core / "need to know"

The order for Mounting is:

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

The order for Updating is:

  1. static getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapShotBeforeUpdate()
  5. componentDidUpdate()

The order for Unmounting is:

  1. componentWillUnmount()

The order for Error Handling is:

  1. static getDerivedStateFromError()
  2. componentDidCatch()

75 What are the lifecycle methods going to be deprecated in React v16?

76 What is the purpose of getDerivedStateFromProps() lifecycle method?

77 What is the purpose of getSnapshotBeforeUpdate() lifecycle method?

78 Do Hooks replace render props and higher order components?

79 What is the recommended way for naming components?

80 What is the recommended ordering of methods in component class?

81 What is a switching component?

82 Why we need to pass a function to setState()?

React may update via setState() asyncronously. Therefore, the value of state when an a plain object is passed to setState is unreliable as the actual update may happen async.

You can pass an updater function to setState() which will force React to execute setState immediately and update the UI with the value returned from the updater function.

83 What is strict mode in React?

84 What are React Mixins?

85 Why is isMounted() an anti-pattern and what is the proper solution?

86 What are the Pointer Events supported in React?

87 Why should component names start with capital letter?

React interprests JSX tags that start with lowercase letters as native DOM nodes. Therefore, React components must be uppercase to be recognized as React components and not React elements.

88 Are custom DOM attributes supported in React v16?

89 What is the difference between constructor and getInitialState?

90 Can you force a component to re-render without calling setState?

91 What is the difference between super() and super(props) in React using ES6 classes?

92 How to loop inside JSX?

93 How do you access props in attribute quotes?

94 What is React PropType array with shape?

95 How to conditionally apply class attributes?

96 What is the difference between React and ReactDOM?

97 Why ReactDOM is separated from React?

98 How to use React label element?

99 How to combine multiple inline style objects?

100 How to re-render the view when the browser is resized?

101 What is the difference between setState and replaceState methods?

102 How to listen to state changes?

103 What is the recommended approach of removing an array element in react state?

104 Is it possible to use React without rendering HTML?

105 How to pretty print JSON with React?

Use a formatting library. I prefer Prettier; then everyone on the development can use whatever IDE settings they want to develop and Prettier will make sure their code is formatted according the project's guidelines before commiting (assuming use of pre-commit hooks).

106 Why you can't update props in React?

107 How to focus an input element on page load?

108 What are the possible ways of updating objects in state?

109 Why function is preferred over object for setState?

Using a function ensures that state is updated immediately instead of async. In short, it makes the calculating state more deterministic and therefore more reliable.

110 How can we find the version of React at runtime in the browser?

111 What are the approaches to include polyfills in your create-react-app?

112 How to use https instead of http in create-react-app?

113 How to avoid using relative path imports in create-react-app?

114 How to add Google Analytics for react-router?

115 How to update a component every second?

116 How do you apply vendor prefixes to inline styles in React?

117 How to import and export components using react and ES6?

118 What are the exceptions on React component naming?

119 Why is a component constructor called only once?

120 How to define constants in React?

121 How to programmatically trigger click event in React?

122 Is it possible to use async/await in plain React?

123 What are the common folder structures for React?

124 What are the popular packages for animation?

125 What is the benefit of styles modules?

126 What are the popular React-specific linters?

127 How to make AJAX call and In which component lifecycle methods should I make an AJAX call?

128 What are render props?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment