All interview topics
Full-Stack, Web & Mobile

React Interview Questions and Answers

Practice React interview questions and answers organized by difficulty, with revealable explanations and related topics.

130 questionsEntry → Expert

Entry questions

9 questions
  1. Question 1
    Entry

    What is the use of refs ?

    • React
    Reveal answer

    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 ref={this.myRef} />; }
    }
    
  2. Question 2
    Entry

    What are React Hooks?

    • React React Hooks
    Reveal answer

    Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

  3. Question 3
    Entry

    What are the advantages of ReactJS?

    • React
    Reveal answer

    Below are the advantages of ReactJS:

    1. Increases the application’s performance with Virtual DOM

    2. JSX makes code is easy to read and write

    3. It renders both on client and server side

    4. Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library

    5. Easy to write UI Test cases and integration with tools such as JEST.

  4. Question 4
    Entry

    What is Context API in ReactJS?

    • React
    Reveal answer

    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.

    // Context lets us pass a value deep into the component tree
    // without explicitly threading it through every component.
    // Create a context for the current theme (with "light" as the default).
    const ThemeContext = React.createContext('light');
    class App extends React.Component {
      render() {
        // Use a Provider to pass the current theme to the tree below.
        // Any component can read it, no matter how deep it is.
        // In this example, we're passing "dark" as the current value.
        return (
        <ThemeContext.Provider value="dark">
        <Toolbar />
        </ThemeContext.Provider>
      );
    }
    }// A component in the middle doesn't have to
    // pass the theme down explicitly anymore.
    function Toolbar() {
      return (
      <div>
      <ThemedButton />
      </div>
    );
    }
    class ThemedButton extends React.Component {
      // Assign a contextType to read the current theme context.
      // React will find the closest theme Provider above and use its value.
      // In this example, the current theme is "dark".
      static contextType = ThemeContext;
      render() {
        return <Button theme={this.context} />;
      }
    }
    
  5. Question 5
    Entry

    What are props in React?

    • React
    Reveal answer

    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:

    1. Pass custom data to your React component.
    2. Trigger state changes.
    3. Use via this.props.reactProp inside component's render() method. For example, let us create an element with reactProp property,
    <Element reactProp = "1" />
    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;
    
  6. Question 6
    Entry

    What are the major features of ReactJS?

    • React
    Reveal answer

    The major features of ReactJS are as follows, 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

  7. Question 7
    Entry

    How would you write an inline style in React?

    • React
    Reveal answer

    For example:

    <div style={{ height: 10 }}>
    
  8. Question 8
    Entry

    What is React?

    • React
    Reveal answer

    React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications. React’s core purpose is to build UI components; it is often referred to as just the “V” (View) in an “MVC” architecture.

  9. Question 9
    Entry

    How does React work?

    • React
    Reveal answer

    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.

Junior questions

34 questions
  1. Question 1
    Junior

    What is the difference between state and props ?

    • React
    Reveal answer

    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. i.e, Props get passed to the component similar to function parameters State is managed within the component similar to variables declared within a function.

  2. Question 1
    Junior

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

    • React
    Reveal answer

    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 this callback function.

    setState({name: 'sudheer'}, () => console.log('The name has updated and component re-rendered'));
    
  3. Question 1
    Junior

    Provide an example of any simple Custom React Hook. Why do we need Custom Hooks?

    • React React Hooks
    Reveal answer

    A Custom Hook is a stateful function that uses other react built-in hooks (e.g. useState , useCallback etc.) that can wrap around the stateful logic that you wanted to gather in one place and avoid copying and pasting the same logic in multiple components. Consider the increment/decriment custom hook:

    const useCounter = () => {
      const [counter, setCounter] = useState(0);
      return {
        counter,
        // counter value
        increment: () => setCounter(counter + 1),
        // function 1
        decrement: () => setCounter(counter - 1)
        // function 2
      };
    };
    

    and then in your component you can use it as follows:

    const Component = () => {
      const { counter, increment, decrement } = useCounter();
      return (
      <div>
      <span onClick={decrement}>-</span>
      <span style={{ padding: "10px" }}>{counter}</span>
      <span onClick={increment}>+</span>
      </div>
    );
    }
    
  4. Question 2
    Junior

    How to access DOM elements in React?

    • React Hooks React
    Reveal answer

    One of the useful application of the useRef() hook is to access DOM elements. This is performed in 3 steps:

    1. Define the reference to access the element const elementRef = useRef() ;
    2. Assign the reference to ref attribute of the element: ;
    3. After mounting, elementRef.current points to the DOM element. Consider:
    import { useRef, useEffect } from 'react';
    function AccessingElement() {
      const elementRef = useRef();
      useEffect(() => {
        const divElement = elementRef.current;
        console.log(divElement);
        // logs <div>I'm an element</div>
      }, []);
    return (
    <div ref={elementRef}>
    I'm an element
    </div>
    );
    }
    
  5. Question 2
    Junior

    How to create refs in React?

    • React
    Reveal answer

    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 with in constructor.

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
    
    render() {
      return <div ref={this.myRef} />;
    }
    }
    

    And:

    class UserForm extends Component {
      handleSubmit = () => {
        console.log("Input Value is: ", this.input.value)
      }
    render () {
      return (
      <form onSubmit={this.handleSubmit}>
      <input
      type='text'
      ref={(input) => this.input = input} /> // Access DOM input in handle submit
      <button type='submit'>Submit</button>
      </form>
    )
    }
    }
    

    We can also use it in functional components with the help of closures.

  6. Question 3
    Junior

    How to call loading function with React useEffect only once?

    • React React Hooks
    Reveal answer

    If you only want to run the function given to useEffect after the initial render, you can give it an

    empty array []
    

    as the second argument. For example:

    function MyComponent(){
      useEffect(() => {
        loadDataOnlyOnce();
      }, []);
    return <div> { /*...*/} </div>;
    }
    
  7. Question 3
    Junior

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

    • React
    Reveal answer

    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.

    render () {
      return (
      <ul>
      {this.state.todoItems.map(({task, uid}) => {
          return <li key={uid}>{task}</li>
        })}
    </ul>
    )
    }
    

    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.

  8. Question 5
    Junior

    What are advantages of using React Hooks?

    • React React Hooks
    Reveal answer

    Primarily, hooks in general enable the extraction and reuse of stateful logic that is common across multiple components without the burden of higher order components or render props. Hooks allow to easily manipulate the state of our functional component without needing to convert them into class components. Hooks don’t work inside classes (because they let you use React without classes). By using them, we can totally avoid using lifecycle methods, such as componentDidMount , componentDidUpdate , componentWillUnmount . Instead, we will use built-in hooks like useEffect .

  9. Question 6
    Junior

    What are Stateless components in React?

    • React
    Reveal answer

    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. Stateful/Container/Smart component:

    class Main extends Component {
      constructor() {
        super()
        this.state = {
          books: []
        }
    }
    render() {
      <BooksList books={this.state.books} />
    }
    }
    Stateless/Presentational/Dumb component:
    const BooksList = ({books}) => {
      return (
      <ul>
      {books.map(book => {
    

    return book

    })}
    </ul>
    )
    }
    

    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.

  10. Question 7
    Junior

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

    • React
    Reveal answer

    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:

    render() {
      // React does *not* create a new div. It renders the children into `domNode`.
      // `domNode` is any valid DOM node, regardless of its location in the DOM.
      return ReactDOM.createPortal(
      this.props.children,
    
      domNode );
    }
    

    A typical use case for portals is when a parent component has an overflow: hidden or z-index style, but you need the child to visually “break out” of its container.

  11. Question 8
    Junior

    What are Fragments in React?

    • React
    Reveal answer

    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.

    render() {
      return (
      <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
      </React.Fragment>
    );
    }
    

    There is also a shorter syntax:

    render() {
      return (
      <>
      <ChildA />
      <ChildB />
      <ChildC />
      </>
    );
    }
    
  12. Question 9
    Junior

    What are Controlled components in ReactJS?

    • React
    Reveal answer

    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".

    // Controlled:
    <input type="text" value={value} onChange={handleChange} />
    
  13. Question 10
    Junior

    What is JSX?

    • React
    Reveal answer

    JSX is a syntax notation for JavaScript XML (XML-like syntax extension to ECMAScript). It stands for JavaScript XML. It provides expressiveness of JavaScript along with HTML like template syntax. For example, the below text inside h1 tag return as javascript function to the render function,

    render(){
      return(
      <div>
      <h1> Welcome to React world!!</h1>
      </div>
    );
    }
    
  14. Question 10
    Junior

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

    • React
    Reveal answer

    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 this callback function.

    setState({name: 'sudheer'}, () => console.log('The name has updated and component re-rendered'));
    
  15. Question 11
    Junior

    What is the difference between Element and Component in ReactJS?

    • React
    Reveal answer

    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 createElement returns as object as below,

    {
      type: 'div',
      props: {
        children: 'Login',
        id: 'login-btn'
      }
    }
    

    And finally it renders to the DOM using ReactDOM.render as below,

    <div id='login-btn'>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 an element tree as the output. JSX transpiled as createElement at the end.

    function Button ({ onLogin }) {
      return React.createElement(
      'div',
      {id: 'login-btn', onClick: onLogin},
      'Login'
    )
    }
    
  16. Question 11
    Junior

    What is the difference between a Presentational component and a Container component?

    • React
    Reveal answer

    Presentational components are concerned with how things look. They generally receive data and callbacks exclusively via props. These components rarely have their own state, but when they do it generally concerns UI state, as opposed to data state. Container components are more concerned with how things work. These components provide the data and behavior to presentational or other container components. They call Flux actions and provide these as callbacks to the presentational components. They are also often stateful as they serve as data sources.

  17. Question 12
    Junior

    What are inline conditional expressions in ReactJS?

    • React
    Reveal answer

    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(&&).

    if(this.state.mode === 'view') {
      return (
      <button onClick={this.handleEdit}>
      Edit
      </button>
    );
    } else {
      return (
      <button onClick={this.handleSave}>
      Save
      </button>
    );
    }
    // or
    {
      view
      ? null
      : (
      <p>
      <input
      onChange={this.handleChange}
      value={this.state.inputText} />
      </p>
    )
    }
    
  18. Question 12
    Junior

    What is state in React?

    • React
    Reveal answer

    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. Consider:

    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>
    );
    }
    }
    
  19. Question 13
    Junior

    What happens when you call setState ?

    • React
    Reveal answer

    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.

  20. Question 13
    Junior

    What are two types of components in ReactJS?

    • React
    Reveal answer

    There are two possible ways to create ReactJS Components.

    1. Functional components: This is the simplest way to create ReactJS components. It accepts props as an Object and returns ReactJS elements. We call it as “functional” because those are pure JavaScript functions.
    function Greeting(props) {
      return <h1> Hello, {props.message}</h1>
    }
    
    1. Class components: You can also use Es6 class to define component. The above functional component can be written as below,
    class Greeting extends React.Component {
      render() {
        return <h1>Hello, {this.props.message}</h1>;
      }
    }
    
  21. Question 14
    Junior

    What are Higher-Order Components (HOC) in React?

    • React
    Reveal answer

    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.

    const EnhancedComponent = higherOrderComponent(WrappedComponent);
    

    HOC can be used for many use cases as below,

    1. Code reuse, logic and bootstrap abstraction
    2. Render High jacking
    3. State abstraction and manipulation
    4. Props manipulation
  22. Question 14
    Junior

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

    • React
    Reveal answer

    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. Most native React form components support both controlled and uncontrolled usage:

    // Controlled:
    <input type="text" value={value} onChange={handleChange} />
    // Uncontrolled:
    <input type="text" defaultValue="foo" ref={inputRef} />
    // Use `inputRef.current.value` to read the current value of <input>
    In most (or all) cases you should use controlled components.
    
  23. Question 15
    Junior

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

    • React
    Reveal answer

    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. Passing props:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        console.log(this.props);
        // Prints { name: 'sudheer',age: 30 }
      }
    }
    
    Not passing props:
    class MyComponent extends React.Component {
      constructor(props) {
        super();
        console.log(this.props);
        // Prints undefined
        // But Props parameter is still available
        console.log(props);
        // Prints { name: 'sudheer',age: 30 }
      }
    render() {
      // No difference outside constructor
      console.log(this.props)
      // Prints { name: 'sudheer',age: 30 }
    }
    }
    

    The above code snippets reveals that this.props behavior is different only with in the constructor. It would be same outside the constructor.

  24. Question 15
    Junior

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

    • React
    Reveal answer

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

  25. Question 16
    Junior

    What is Reconciliation in ReactJS?

    • React
    Reveal answer

    When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

  26. Question 16
    Junior

    What happens during the lifecycle of a React component?

    • React
    Reveal answer

    At the highest level, React components have lifecycle events that fall into three general categories:

    1. Initialization
    2. State/Property Updates
    3. Destruction
  27. Question 17
    Junior

    What are Stateful components in React?

    • React
    Reveal answer

    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
    }
    }
    
  28. Question 17
    Junior

    How is React different from AngularJS (1.x)?

    • React
    Reveal answer

    For example, AngularJS (1.x) approaches building an application by extending HTML markup and injecting various

    constructs (e.g. Directives, Controllers, Services) at runtime. As a result, AngularJS is very opinionated about the
    

    greater architecture of your application — these abstractions are certainly useful in some cases, but they come at the cost of flexibility. By contrast, React focuses exclusively on the creation of components, and has few (if any) opinions about an application’s architecture. This allows a developer an incredible amount of flexibility in choosing the architecture they deem “best” — though it also places the responsibility of choosing (or building) those parts on the developer.

  29. Question 18
    Junior

    What are the advantages of using React?

    • React
    Reveal answer

    It is easy to know how a component is rendered, you just need to look at the render function. JSX makes it easy to read the code of your components. It is also really easy to see the layout, or how components are plugged/combined with each other. You can render React on the server-side. This enables improves SEO and performance. It is easy to test. You can use React with any framework (Backbone.js, Angular.js) as it is only a view layer.

  30. Question 18
    Junior

    What are refs used for in React?

    • React
    Reveal answer

    Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.

    class UnControlledForm extends Component {
      handleSubmit = () => {
        console.log("Input Value: ", this.input.value)
      }
    render () {
      return (
      <form onSubmit={this.handleSubmit}>
      <input
      type='text'
      ref={(input) => this.input = input} />
      <button type='submit'>Submit</button>
      </form>
    )
    }
    }
    

    Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function. It’s often misconstrued that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.

    function CustomForm ({handleSubmit}) {
      let inputElement
      return (
      <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
      type='text'
      ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
      </form>
    )
    }
    
  31. Question 19
    Junior

    What are the limitations of React?

    • React
    Reveal answer

    Below are the list of limitations:

    1. React is just a view library, not a full-blown framework
    2. There is a learning curve for beginners who are new to web development.
    3. Integrating React.js into a traditional MVC framework requires some additional configuration
    4. The code complexity increases with inline templating and JSX.
    5. Too many smaller components leading to over-engineering or boilerplate
  32. Question 19
    Junior

    What is the difference between state and props ?

    • React
    Reveal answer

    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.

  33. Question 20
    Junior

    What is the difference between Component and Container in Redux?

    • React Redux
    Reveal answer

    Component 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.

  34. Question 20
    Junior

    What are the differences between a Class component andFunctional component?

    • React
    Reveal answer

    Class Components 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

Mid questions

47 questions
  1. Question 1
    Mid

    What is Lifting State Up in ReactJS?

    • React
    Reveal answer

    When several components need to share the same changing data then it is recommended to lifting the shared state up to their closest common ancestor. For example, if two child components sharing the same data from its parent then move the state to parent instead of maintaining the local state inn both child components.

  2. Question 1
    Mid

    What is equivalent of the following using React.createElement ?

    • React
    Reveal answer

    Question:

    const element = (
    <h1 className="greeting">
    Hello, world!
    </h1>
    );
    

    What is equivalent of the following using React.createElement ? Answer:

    const element = React.createElement(
    'h1',
    {className: 'greeting'},
    'Hello, world!'
    );
    
  3. Question 2
    Mid

    What is the difference between HTML and React event handling?

    • React
    Reveal answer

    Below are the few differences between HTML and React event handling:

    1. In HTML, the event name should be in lowercase.
    <button onclick="activateLasers()">
    

    Whereas in ReactJS it follows camelCase convention,

    <button onClick={activateLasers}>
    
    1. In HTML, you can return false to prevent default behavior,
    2. Whereas in ReactJS you must call preventDefault explicitly,
    function handleClick(e) {
      e.preventDefault();
      console.log('The link was clicked.');
    }
    
  4. Question 2
    Mid

    What does Batching mean in ReactJS?

    • React React Hooks
    Reveal answer

    Batching is nothing but grouping React multiple state updates together into a single render state to achieve better computational performance. Until React 18, we only batched updates during the React event handlers. Updates inside of promises , setTimeout , native event handlers, or any other event were not batched in React by default.

    function App() {
      const [count, setCount] = useState(0);
      const [flag, setFlag] = useState(false);
      function handleClick() {
        setCount(c => c+1);
        // Does not re-render yet
        setFlag(f => !f);
        // Does not re-render yet
        // React will only re-render once at the end (that's batching!)
      }
    return (
    <div>
    <button onClick={handleClick}>Next</button>
    <h1 style={{color: flag ? "blue": "black"}}>{count}</h1>
    </div>
    )
    }
    
  5. Question 2
    Mid

    Why do class methods need to be bound to a class instance?

    • React
    Reveal answer

    In JavaScript, the value of this changes depending on the current context. Within React class component methods, developers normally expect this to refer to the current instance of a component, so it is necessary tobind these methods to the instance. Normally this is done in the constructor—for example:

    class SubmitButton extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isFormSubmitted: false
        };
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleSubmit() {
      this.setState({
        isFormSubmitted: true
      });
    }
    
    render() {
      return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
    }
    }
    
  6. Question 3
    Mid

    What is Components Composition in React?

    • React
    Reveal answer

    Sometimes we think about components as being “special cases” of other components. For example, we might say that a WelcomeDialog is a special case of Dialog . In React, this is also achieved by components composition, where a more “specific” component renders a more “generic” one and configures it with props:

    function Dialog(props) {
      return (
      <FancyBorder color="blue">
      <h1 className="Dialog-title">
      {props.title}
      </h1>
      <p className="Dialog-message">
      {props.message}
      </p>
      </FancyBorder>
    );
    }
    function WelcomeDialog() {
      return (
      <Dialog
      title="Welcome"
      message="Thank you for visiting our spacecraft!" />
    );
    }
    
  7. Question 3
    Mid

    What do these three dots ( ... ) in React do?

    • React
    Reveal answer

    Problem

    What does the ... do in this React (using JSX) code and what is it called?

    <Modal {...this.props} title='Modal heading' animation={false}/>
    
    ### Solution
    That's property spread notation. It was added in ES2018 (spread for arrays/iterables was earlier, ES2015).
    

    For instance, if this.props contained a: 1 and b: 2 , then

    <Modal {...this.props} title='Modal heading' animation={false}>
    would be the same as:
    <Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
    Spread notation is handy not only for that use case, but for creating a new object with most (or all) of the
    

    properties of an existing object — which comes up a lot when you're updating state, since you can't modify state directly:

    this.setState(prevState => {
      return {foo: {...prevState.foo, a: "updated"}};
    });
    
  8. Question 3
    Mid

    Why React uses className over class attribute?

    • React
    Reveal answer

    class is a keyword in javascript and JSX is an extension of javascript. That's the principal reason why React uses className instead of class.

    render() {
      return <span className="menu navigation-menu">Menu</span>
    }
    
  9. Question 4
    Mid

    What's the difference between useRef and createRef ?

    • React
    Reveal answer

    The difference is:

    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.

  10. Question 4
    Mid

    What's wrong with using Context in React?

    • React
    Reveal answer

    Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult. If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context. For example, consider a Page component that passes a user and avatarSize prop several levels down so that deeply nested Link and Avatar components can read it:

    <Page user={user} avatarSize={avatarSize} />
    // ... which renders ...
    <PageLayout user={user} avatarSize={avatarSize} />
    // ... which renders ...
    <NavigationBar user={user} avatarSize={avatarSize} />
    // ... which renders ...
    <Link href={user.permalink}>
    <Avatar user={user} size={avatarSize} />
    </Link>
    

    It might feel redundant to pass down the user and avatarSize props through many levels if in the end only the Avatar component really needs it. It’s also annoying that whenever the Avatar component needs more props from the top, you have to add them at all the intermediate levels too.

  11. Question 4
    Mid

    What is equivalent of this code using React Hooks?

    • React React Hooks
    Reveal answer

    Problem

    Let's say in our project we have componentWillUnmount that is used for cleanup (like removing event listeners, cancel the timer etc). How to refactor this code using React Hooks?

    componentDidMount() {
      window.addEventListener('mousemove', () => {})
    }
    componentWillUnmount() {
      window.removeEventListener('mousemove', () => {})
    }
    
    ### Solution
    

    React Hooks equivalent of above code will be as follows

    useEffect(() => {
      window.addEventListener('mousemove', () => {});// returned function will be called on component unmount
      return () => {
        window.removeEventListener('mousemove', () => {})
      }
    }, [])
    
  12. Question 4
    Mid

    What is children prop ?

    • React
    Reveal answer

    Children is a prop ( this.prop.children ) that allow you to pass components as data to other components, just like any other prop you use. There are a number of methods available in the React API to work with this prop. These include: React.Children.map , React.Children.forEach , React.Children.count , React.Children.only , React.Children.toArray . A simple usage of children prop looks as below,

    var MyDiv = React.createClass({
      render: function() {
        return <div>{this.props.children}</div>;
      }
    });
    ReactDOM.render(
    <MyDiv>
    <span>Hello</span>
    <span>World</span>
    </MyDiv>,
    node
    );
    
  13. Question 5
    Mid

    How would you pass data from child to parent component in React?

    • React
    Reveal answer

    Often, several components need to reflect the same changing data. 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. A common technique for these situations is to lift the state up to the first common ancestor of all the components that need to use the state (i.e. the PageComponent in this case) and pass down the state and state- altering functions to the child components as props.

    function PageComponent() {
      const [count, setCount] = useState(0);
      const increment = () => {
        setCount(count + 1)
      }
    return (
    <div className="App">
    <ChildComponent onClick={increment} count={count} />
    <h2>count {count}</h2>
    (count should be updated from child)
    </div>
    );
    }
    const ChildComponent = ({ onClick, count }) => {
      return (
      <button onClick={onClick}>
      Click me {count}
      </button>
    )
    };
    
  14. Question 5
    Mid

    What's wrong with that code?

    • React
    Reveal answer

    Problem

    Consider: this.setState({ counter: this.state.counter + this.props.increment,

    });
    

    What's wrong with that code?

    Solution

    Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

    // Correct
    this.setState((state, props) => ({
      counter: state.counter + props.increment
    }));
    
  15. Question 5
    Mid

    How to bind methods or event handlers in JSX callbacks?

    • React
    Reveal answer

    There are 3 possible ways to achieve,

    1. Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies for ReactJS event handlers defined as class methods. Normally we bind them in constructor as follows,
    constructor(props) {
      super(props);
      this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
      // Perform some logic
    }
    
    1. Public class fields syntax: If you don’t like to use bind approach then public class fields syntax can be used to correctly bind callbacks
    handleClick = () => {
      console.log('this is:', this);
    }
    <button onClick={this.handleClick}>
    Click me
    </button>
    
    1. Arrow functions in callbacks: You can use arrow functions directly in the callbacks as below
    <button onClick={(e) => this.handleClick(e)}>
    Click me
    </button>
    
  16. Question 6
    Mid

    When would you use useRef ?

    • React Hooks React
    Reveal answer

    The main use cases:

    1. To store a ref to DOM elements so you can later do something with them: Consider:
    function TextInputWithFocusButton() {
      const inputEl = useRef(null);
      const onButtonClick = () => {
    
        inputEl.current.focus();
      };
    return (
    <>
    <input ref={inputEl} type="text"/>
    <button onClick={onButtonClick}>Focus the input</button>
    </>
    );
    }
    2. To store values
    without triggering
    re-renders:
    

    Consider:

    function Counter(){
      const [count, setCount] = useState(0);
      const prevCountRef = useRef();
      useEffect(() => {
        prevCountRef.current = count;
      });
    const prevCount = prevCountRef.current;
    return <h1>Now: {count}, before: {prevCount} </h1>;
    }
    
  17. Question 6
    Mid

    What is the point of shouldComponentUpdate() method?

    • React
    Reveal answer

    It's used for performance reasons, for example if the implementor of a component knows for sure that a particular property change does not necessitate a re-render, they could return false from this method and skip the re-render.

  18. Question 7
    Mid

    How can I make use of Error Boundaries in functional React components?

    • React React Hooks
    Reveal answer

    As of v16.2.0, there's no way to turn a functional component into an error boundary. The componentDidCatch() method works like a JavaScript catch {} block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once and use it throughout your application. Also bear in mind that try/catch blocks won't work on all cases. If a component deep in the hierarchy tries to update and fails, the try/catch block in one of the parents won't work -- because it isn't necessarily updating together with the child. A few third party packages on npm implement error boundary hooks.

  19. Question 7
    Mid

    What is prop drilling and how can you avoid it?

    • React
    Reveal answer

    When building a React application, there is often the need for a deeply nested component to use data provided by another component that is much higher in the hierarchy. The simplest approach is to simply pass a prop from each component to the next in the hierarchy from the source component to the deeply nested component. This is called prop drilling. The primary disadvantage of prop drilling is that components that should not otherwise be aware of the data become unnecessarily complicated and are harder to maintain. To avoid prop drilling, a common approach is to use React context. This allows a Provider component that supplies data to be defined, and allows nested components to consume context data via either a Consumer component or a useContext hook.

  20. Question 7
    Mid

    What does shouldComponentUpdate do and why is it important?

    • React
    Reveal answer

    What shouldComponentUpdate does is it’s a lifecycle method that allows us to opt out of setState reconciliation process for certain components (and their child components). If we know that a certain section of our UI isn’t going to change, there’s no reason to have React go through the trouble of trying to figure out if it should. By returning false from shouldComponentUpdate , React will assume that the current component, and all its child components, will stay the same as they currently are.

  21. Question 8
    Mid

    Do React Hooks cover all use cases for class components?

    • React Hooks React
    Reveal answer

    No, The following methods have not been introduced in Hooks yet: getSnapshotBeforeUpdate getDerivedStateFromError componentDidCatch

  22. Question 8
    Mid

    What are Stateless components in React?

    • React
    Reveal answer

    Stateless components (a flavor of “reusable” components) are nothing more than pure functions that render DOM based solely on the properties provided to them.

    const StatelessCmp = props => {
      return (
      <div className="my-stateless-component">
      {props.name}: {props.birthday}
      </div>
    );
    };// ---
    ReactDOM.render(
    <StatelessCmp name="Art" birthday="10/01/1980" />,
    document.getElementById('main')
    );
    

    This component has no need for any internal state — let alone a constructor or lifecycle handlers. The output of the component is purely a function of the properties provided to it.

  23. Question 9
    Mid

    Compare useState and useReducer implementations

    • React React Hooks
    Reveal answer

    useState updates state with setState , while useReducer with dispatch function. useState passes down all the setState custom helper functions, while useReducer passes down just the dispatch function. useState needs to wrap functions in useCallback (if we want to memorize them), while dispatch function is already memorized. useState easier to write, useReducer is harder to implement and needs more logic to be coded.

  24. Question 9
    Mid

    What are the lifecycle methods of ReactJS class components?

    • React
    Reveal answer

    componentWillMount : Executed before rendering and is used for App level configuration in your root component. componentDidMount : Executed after first rendering and here all AJAX requests, DOM or state updates, and set up eventListeners should occur. componentWillReceiveProps : Executed when particular prop updates to trigger state transitions. shouldComponentUpdate : Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a rerender if component receives new prop. componentWillUpdate : Executed before re-rendering the component when there are pros & state changes confirmed by shouldComponentUpdate which returns true. componentDidUpdate : Mostly it is used to update the DOM in response to prop or state changes. componentWillUnmount : It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

  25. Question 9
    Mid

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

    • React
    Reveal answer

    You can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. It is used to display whatever you include between the opening and closing tags when invoking a component.

    const Picture = (props) => {
      return (
      <div>
      <img src={props.src}/>
      {props.children}
      </div>
    )
    }
    
  26. Question 10
    Mid

    Which lifecycle methods of class component is replaced by useEffect in functional component?

    • React React Hooks
    Reveal answer

    The lifecyce methods replaced by useEffect Hooks of functional component are

    componentDidMount() ,
    componentDidUpdate() , and componentWillUnmount()
    

    componentDidMount : is equivalent for running an effect once. For example:

    useEffect(() => {
      console.log("This is useEffect Hook equivalent of componentDidMount lifecycle method")
    },[]);
    Note:* empty array = useEffect hook
    runs once on mount
    

    componentDidUpdate : is equivalent for running effects when things change For example:

    useEffect(() => {
      console.log("The name props has changed!");
    }, [props.name]);
    componentWillUnmount : To run a
    

    hook as the component is about to unmount, we just have to return a function from the useEffect Hook For example:

    useEffect(() => {
      console.log('running effect');
      return () => {
        console.log('unmount');
      }
    })
    
  27. Question 10
    Mid

    What are the different phases of ReactJS componentlifecycle?

    • React
    Reveal answer

    There are four different phases of React component’s lifecycle:

    1. Initialization: In this phase react component prepares setting up the initial state and default props.
    2. Mounting: The react component is ready to mount in the browser DOM. This phase covers componentWillMount and componentDidMount lifecycle methods.
    3. Updating: In this phase, the component get updated in two ways, sending the new props and updating the state. This phase covers shouldComponentUpdate, componentWillUpdate and componentDidUpdate lifecycle methods.
    4. Unmounting: In this last phase, the component is not needed and get unmounted from the browser DOM. This phase include componentWillUnmount lifecycle method.
  28. Question 10
    Mid

    Name the different lifecycle methods for a class components

    • React
    Reveal answer

    componentWillMount - this is most commonly used for App configuration in your root component. componentDidMount - here you want to do all the setup you couldn’t do without a DOM, and start getting all the data you need. Also if you want to set up eventListeners etc. this lifecycle hook is a good place to do that. componentWillReceiveProps - this lifecyclye acts on particular prop changes to trigger state transitions. shouldComponentUpdate - if you’re worried about wasted renders shouldComponentUpdate is a great place to improve performance as it allows you to prevent a rerender if component receives new prop . shouldComponentUpdate should always return a boolean and based on what this is will determine if the component is rerendered or not. componentWillUpdate - rarely used. It can be used instead of componentWillReceiveProps on a component that also has shouldComponentUpdate (but no access to previous props). componentDidUpdate - also commonly used to update the DOM in response to prop or state changes. componentWillUnmount - here you can cancel any outgoing network requests, or remove all event listeners associated with the component.

  29. Question 11
    Mid

    What are the advantages of Batching in ReactJS?

    • React React Hooks
    Reveal answer

    Batching is great for performance because it avoids unnecessary re-renders. Batching also prevents your component from rendering half-finished states where only one state variable was updated, which may cause bugs. Another reason to use batching is when the web application grows, the number of nested components will increase. Therefore, if a parent component executes an unbatched state updated, the entire component tree will be re-rendered per state update that is expensive.

  30. Question 11
    Mid

    How would you prevent a component from rendering in React?

    • React
    Reveal answer

    Returning null from a component's render method does not affect the firing of the component's lifecycle methods.

  31. Question 12
    Mid

    What is StrictMode in React?

    • React
    Reveal answer

    React's StrictMode is sort of a helper component that will help you write better react components, you can wrap a set of components with and it'll basically: Verify that the components inside are following some of the recommended practices and warn you if not in the console. Verify the deprecated methods are not being used, and if they're used strict mode will warn you in the console. Help you prevent some side effects by identifying potential risks.

  32. Question 12
    Mid

    What are Uncontrolled components?

    • React
    Reveal answer

    The Uncontrolled Component are the 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 For example, in the below UserProfile component, the name input accessed using ref as below,

    class UserProfile extends React.Component {
      constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.input = React.createRef();
      }
    handleSubmit(event) {
      alert('A name was submitted: ' + this.input.current.value);
      event.preventDefault();
    }
    render() {
      return (
      <form onSubmit={this.handleSubmit}>
      <label>
      Name:
      <input type="text" ref={this.input} />
      </label>
      <input type="submit" value="Submit" />
      </form>
    );
    }
    }
    

    In most cases, it is recommend using controlled components to implement forms.

  33. Question 13
    Mid

    What are Error Boundaries in ReactJS?

    • React
    Reveal answer

    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. A class component becomes an error boundary if it defines a new lifecycle method called

    componentDidCatch(error, info)
    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
    componentDidCatch(error, info) {
      // Display fallback UI
      this.setState({ hasError: true });
      // You can also log the error to an error reporting service
      logErrorToMyService(error, info);
    }
    render() {
      if (this.state.hasError) {
        // You can render any custom fallback UI
        return <h1>Something went wrong.</h1>;
    
      }
    return this.props.children;
    }
    }
    

    After that use it as a regular component

  34. Question 13
    Mid

    What is the difference between ShadowDOM and VirtualDOM?

    • React
    Reveal answer

    Virtual DOM Virtual DOM is about avoiding unnecessary changes to the DOM, which are expensive performance-wise, because changes to the DOM usually cause re-rendering of the page. Virtual DOM also allows to collect several changes to be applied at once, so not every single change causes a re-render, but instead re-rendering only happens once after a set of changes was applied to the DOM. Shadow DOM

    Shadow dom is mostly about encapsulation of the implementation. A single custom element can implement more-or-less complex logic combined with more-or-less complex DOM. An entire web application of arbitrary complexity can be added to a page by an import and but also simpler reusable and composable components can be implemented as custom elements where the internal representation is hidden in the shadow DOM like .

  35. Question 14
    Mid

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

    • React
    Reveal answer

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

    render() {
      // Wrong way: handleClick is called instead of passed as a reference!
      return <button onClick={this.handleClick()}>Click Me</button>
    }
    

    Instead, pass the function itself without parenthesis:

    render() {
      // Correct way: handleClick is passed as a reference!
      return <button onClick={this.handleClick}>Click Me</button>
    }
    
  36. Question 14
    Mid

    What are forward refs ?

    • React
    Reveal answer

    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) => (
    <button ref={ref} className="CustomButton">
    {props.children}
    </button>
    ));// Create ref to the DOM button:
    const ref = React.createRef();
    <ButtonElement ref={ref}>Forward Ref</ButtonElement>;
    
  37. Question 15
    Mid

    What is the difference between HTML and React event handling?

    • React
    Reveal answer

    Below are the few differences between HTML and React event handling:

    1. In HTML, the event name should be in lowercase.
    <button onclick="activateLasers()">
    

    Whereas in ReactJS it follows camelCase convention,

    <button onClick={activateLasers}>
    
    1. In HTML, you can return false to prevent default behavior,
    2. Whereas in ReactJS you must call preventDefault explicitly,
    function handleClick(e) {
      e.preventDefault();
      console.log('The link was clicked.');
    }
    
  38. Question 15
    Mid

    What is Key and benefit of using it in lists?

    • React
    Reveal answer

    A key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed. For example, most often we use IDs from your data as keys

    const todoItems = todos.map((todo) =>
    <li key={todo.id}>
    {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 key={index}>
    {todo.text}
    </li>
    );
    

    Note:

    1. We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state

    2. If you extract list item as separate component then apply keys on list component instead li tag. There will be a warning in the console if the key is not present on list items.

  39. Question 16
    Mid

    Why we should not update state directly?

    • React
    Reveal answer

    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: The only place you can assign the state is constructor.

  40. Question 16
    Mid

    What are Pure Components?

    • React
    Reveal answer

    PureComponent is exactly the same as 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.

  41. Question 17
    Mid

    What is the significance of key s in ReactJS?

    • React
    Reveal answer

    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: Example:

    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
    <li key={number.toString()}>
    {number}
    </li>
    );
    

    When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).

  42. Question 17
    Mid

    What's the typical flow of data like in a React + Redux app?

    • React
    Reveal answer

    Callback from UI component dispatches an action with a payload, which then is intercepted in a reducer, possibly producing a new application state, which is then propagated down through the tree of components in the application from the Redux store.

  43. Question 18
    Mid

    What is the difference between createElement and cloneElement ?

    • React
    Reveal answer

    createElement is what JSX gets transpiled to and is what React uses to create React Elements (object representations of some UI). cloneElement is used in order to clone an element and pass it new props. They nailed the naming on these two.

  44. Question 18
    Mid

    What's the difference between an Element and a Component in React?

    • React
    Reveal answer

    Elements are the fundamental building blocks of React, and describe what you want to see on the screen. They are just simple JS objects with props, key, ref, and type properties, whereas Components have a render method and optionally accept inputs.

  45. Question 19
    Mid

    What's the typical pattern for rendering a list of components from an array in React?

    • React
    Reveal answer

    Call map on an array with an arrow function that executes for each array element, possibly outputting a React component for each. Consider:

    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
    <li key={number.toString()}>
    {number}
    </li>
    );
    
  46. Question 20
    Mid

    Are you familiar with Flux in the context of React?

    • React
    Reveal answer

    Flux is an architectural pattern that enforces unidirectional data flow — its core purpose is to control derived data so that multiple components can interact with that data without risking pollution. The Flux pattern is generic; it’s not specific to React applications, nor is it required to build a React app. However, Flux is commonly used by React developers because React components are declarative — the rendered UI (View) is simply a function of state (Store data). In the Flux pattern, the Store is the central authority for all data; any mutations to the data must occur within the store. Changes to the Store data are subsequently broadcast to subscribing Views via events. Views then update themselves based on the new state of received data. To request changes to any Store data, Actions may be fired. These Actions are controlled by a central

    Dispatcher;
    

    Actions may not occur simultaneously, ensuring that a Store only mutates data once per Action. The strict unidirectional flow of this Flux pattern enforces data stability, reducing data-related runtime errors throughout an application.

  47. Question 20
    Mid

    What are some limitations of things you shouldn't do in the component's render method in React?

    • React
    Reveal answer

    You cannot modify the component's state (with setState ), nor interact with the browser (do that in componentDidMount ). Render should be a pure function.

Senior questions

30 questions
  1. Question 1
    Senior

    How to apply validation on props in ReactJS?

    • React
    Reveal answer

    When the application is running in development mode, React will automatically check for all props that we set on components to make sure they must right correct and right data type. For incorrect type, it will generate warning messages in the console for development mode whereas it is disabled in production mode due performance impact. The mandatory prop is defined with isRequired. The set of predefined prop types are below

    1. React.PropTypes.string
    2. React.PropTypes.number
    3. React.PropTypes.func
    4. React.PropTypes.node
    5. React.PropTypes.bool For example, we define propTypes for user component as below,
    import PropTypes from 'prop-types';
    class User extends React.Component {
      render() {
        return (
        <h1>Welcome, {this.props.name}</h1>
        <h2>Age, {this.props.age}
      );
    }
    }
    User.propTypes = {
      name: PropTypes.string.isRequired,
      age: PropTypes.number.isRequired
    };
    
  2. Question 2
    Senior

    How would you store non-state/ instance variables in functional React components?

    • React Hooks React
    Reveal answer

    You can use useRef hook (it's the recommended way stated in docs). useRef returns an object whose reference would not change across re-renders, the actual value for foo is then kept in the current property of that object. Declaring variable: const a = useRef(5) // 5 is initial value getting the value: a.current setting the value: a.current = my_value

  3. Question 3
    Senior

    When to use useState vs useReducer ?

    • React React Hooks
    Reveal answer

    The decision of whether to use useState or useReducer isn't always black and white; there are many shades of grey. But, use useState if you have: JavaScript primitives as state Simple state transitions Business logic within your component Different properties that don't change in any correlated way and can be managed by multiple useState hooks use useReducer if you have: JavaScript objects or arrays as state Complex state transitions Complicated business logic more suitable for a reducer function (to separate concern of it) Different properties tied together that should be managed in one state object (when state depends on state)

  4. Question 4
    Senior

    What's the difference between useCallback and useMemo in practice?

    • React React Hooks
    Reveal answer

    With useCallback you memoize functions, useMemo memoizes any computed value:

    const fn = () => 42
    // assuming expensive calculation here
    const memoFn = useCallback(fn, [dep])
    // (1)
    const memoFnReturn = useMemo(fn, [dep])
    // (2)
    (1) will return a memoized version of fn - same reference across multiple renders, as long as dep is the same.
    But
    every time you
    invoke memoFn ,
    that complex computation starts again.
    (2) will invoke fn every time dep changes and remember its
    returned value ( 42 here), which is then stored in
    memoFnReturn .
    
  5. Question 5
    Senior

    When would you use StrictMode component in React?

    • React
    Reveal answer

    I've found it especially useful to implement strict mode when I'm working on new code bases and I want to see what kind of code/components I'm facing. Also if you're on bug hunting mode, sometimes it's a good idea to wrap with the components/blocks of code you think might be the source of the problem.

  6. Question 6
    Senior

    Describe how events are handled in React

    • React
    Reveal answer

    In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent , which is React’s cross-browser wrapper around the browser’s native event. These synthetic events have the same interface as native events you’re used to, except they work identically across all browsers. What’s mildly interesting is that React doesn’t actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn’t need to worry about keeping track of event listeners when updating the DOM.

  7. Question 6
    Senior

    How would you go about investigating slow React application rendering?

    • React
    Reveal answer

    One of the most common issues in React applications is when components re-render unnecessarily. There are two tools provided by React that are helpful in these situations:

    React.memo() : This prevents unnecessary re-rendering of function components
    PureComponent : This prevents unnecessary re-rendering of class components
    

    Both of these tools rely on a shallow comparison of the props passed into the component—if the props have not changed, then the component will not re-render. While both tools are very useful, the shallow comparison brings with it an additional performance penalty, so both can have a negative performance impact if used incorrectly. By using the React Profiler, performance can be measured before and after using these tools to ensure that performance is actually improved by making a given change.

  8. Question 7
    Senior

    Does React re-render all components and sub components every time setState is called?

    • React
    Reveal answer

    By default - yes. There is a method boolean shouldComponentUpdate(object nextProps, object nextState) , each component has this method and it's responsible to determine "should component update (run render function)?" every time you change state or pass new props from parent component. You can write your own implementation of shouldComponentUpdate method for your component, but default implementation always returns true - meaning always re-run render function.

  9. Question 7
    Senior

    When is it important to pass props to super() , and why?

    • React
    Reveal answer

    The only one reason when one needs to pass props to super() is when you want to access this.props in constructor:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props)
        console.log(this.props)
        // -> { icon: 'home', … }
      }
    }
    Not passing:
    class MyComponent extends React.Component {
      constructor(props) {
        super()
        console.log(this.props)
        // -> undefined
        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
      }
    render() {
      // No difference outside constructor
      console.log(this.props)
      // -> { icon: 'home', … }
    }
    }
    

    Note that passing or not passing props to super has no effect on later uses of this.props outside constructor.

  10. Question 8
    Senior

    When would you use flushSync in ReactJS?

    • React React Hooks
    Reveal answer

    React 18 adds out-of-the-box performance improvements by doing more batching (automated) by default. Batching is when React groups multiple state updates into a single re-render for better performance. To opt-out of automatic batching, you can use flushSync so your component will be re-rendered after each state update. You might need it when for example some code may depend on reading something from the DOM immediately after a state change. Consider with automated batching:

    function handleClick() {
      setCount(c => c + 1);
      setFlag(f => !f);
      // React will only re-render once at the end (that's batching!)
    }
    

    Consider with flushSync :

    import { flushSync } from 'react-dom';
    function handleClick() {
      flushSync(() => {
        setCounter(c => c + 1);
      });
    // React has updated the DOM by now
    flushSync(() => {
      setFlag(f => !f);
    });
    // React has updated the DOM by now
    }
    
  11. Question 9
    Senior

    When is it important to pass props to super() , and why?

    • React
    Reveal answer

    The only one reason when one needs to pass props to super() is when you want to access this.props in constructor:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props)
        console.log(this.props)
        // -> { icon: 'home', … }
      }
    }
    Not passing:
    class MyComponent extends React.Component {
      constructor(props) {
        super()
        console.log(this.props)
        // -> undefined
        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
      }
    render() {
      // No difference outside constructor
      console.log(this.props)
      // -> { icon: 'home', … }
    }
    }
    

    Note that passing or not passing props to super has no effect on later uses of this.props outside constructor.

  12. Question 10
    Senior

    What is the difference between using constructor vs getInitialState in React?

    • React
    Reveal answer

    The difference between constructor and getInitialState is the difference between ES6 and ES5 itself. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass .

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          /* initial state */ };
      }
    }
    

    is equivalent to

    var MyComponent = React.createClass({
      getInitialState() {
        return {
          /* initial state */ };
      },
    });
    
  13. Question 11
    Senior

    Can you force a React component to rerender without calling setState ?

    • React
    Reveal answer

    In your component, you can call this.forceUpdate() to force a rerender. Another way is this.setState(this.state); Note that forceUpdate should be avoided because it deviates from a React mindset. The React docs cite an example of when forceUpdate might be used: By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your

    render() method depends on some other data, you can tell React that it needs to re-run render() by calling
    forceUpdate().
    
  14. Question 11
    Senior

    What is the purpose of super(props) ?

    • React
    Reveal answer

    When you pass props to super , the props get assigned to this . Take a look at the following scenario:

    constructor(props) {
      super();
      console.log(this.props)
      //undefined
    }
    

    How ever when you do :

    constructor(props) {
      super(props);
      console.log(this.props)
      //props will get logged.
    }
    

    Note that passing or not passing props to super has no effect on later uses of this.props outside constructor . That is render , shouldComponentUpdate , or event handlers always have access to it.

  15. Question 12
    Senior

    Explain the Virtual DOM concept in React

    • React
    Reveal answer

    There are in fact 2 problems that need to be solved here

    1. When do I re-render? Answer: When I observe that the data is dirty.
    2. How do I re-render efficiently? Answer: Using a virtual DOM to generate a real DOM patch In React, each of your components have a state. This state is like an observable you might find in knockout or other MVVM style libraries. Essentially, React knows when to re-render the scene because it is able to observe when this data changes. Dirty checking is slower than observables because you must poll the data at a regular interval and check all of the values in the data structure recursively. By comparison, setting a value on the state will signal to a listener that some state has changed, so React can simply listen for change events on the state and queue up re-rendering. The virtual DOM is used for efficient re-rendering of the DOM. This isn't really related to dirty checking your data. You could re-render using a virtual DOM with or without dirty checking. With ReactJS, each time a change is
    triggered (by a query or a user’s action, for instance), the entire virtual DOM is updated. ReactJS keeps two
    

    versions of the virtual DOM in memory — an updated virtual DOM and a copy made before the update. After the update, ReactJS compares these two versions to find the elements that have changed. Then it updates only the part of the real DOM that has changed. There is some overhead in computing the diff between two virtual trees, but the virtual DOM diff is about understanding what needs updating in the DOM and not whether or not your data has changed.

  16. Question 12
    Senior

    How to create Props Proxy for HOC component?

    • React
    Reveal answer

    You can add/edit props passed to the Component as a props proxy as below

    function HOC(WrappedComponent) {
      return class Test extends Component {
        render() {
          const newProps = {
            title: 'New Header',
            footer: false,
            showFeatureX: false,
            showFeatureY: true
          };
        return <WrappedComponent {...this.props} {...newProps} />
      }
    }
    }
    
  17. Question 13
    Senior

    If you created a React element like Twitter below, what would the component definition of Twitter look like?

    • React
    Reveal answer

    Question: If you created a React element like Twitter below, what would the component definition of Twitter look like?

    <Twitter username='tylermcginnis33'>
    {(user) => user === null
      ? <Loading />
      : <Badge info={user} />}
    </Twitter>
    import React, { Component, PropTypes } from 'react'
    import fetchUser from 'twitter'
    // fetchUser take in a username returns a promise
    // which will resolve with that username's data.
    class Twitter extends Component {
      // finish this
    }
    Answer:
    

    Instead of another component as you’ve probably seen before, the Twitter component’s child is a function. What this means is that in the implementation of the Twitter component, we’ll need to treat props.children as a function.

    import React, { Component, PropTypes } from 'react'
    import fetchUser from 'twitter'
    class Twitter extends Component {
      state = {
        user: null,
    
      }
    static propTypes = {
      username: PropTypes.string.isRequired,
    }
    componentDidMount () {
      fetchUser(this.props.username)
      .then((user) => this.setState({user}))
    }
    render () {
    

    return this.props.children(this.state.user)

    }
    }
    

    What’s great about this pattern is that we’ve decoupled our parent component from our child component. The parent component manages the state and the consumer of the parent component can decide in which way they’d like to apply the arguments they receive from the parent to their UI.

  18. Question 13
    Senior

    Why does React use SyntheticEvents ?

    • React
    Reveal answer

    React implements a synthetic events system that brings consistency and high performance to React apps and interfaces. It achieves consistency by normalizing events so that they have the same properties across different browsers and platforms. A synthetic event is a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault() , except the events work identically across all browsers. It achieves high performance by automatically using event delegation. In actuality, React doesn’t attach event handlers to the nodes themselves. Instead, a single event listener is attached to the root of the document. When an event is fired, React maps it to the appropriate component element.

  19. Question 14
    Senior

    Explain why and when would you use useMemo() ?

    • React React Hooks
    Reveal answer

    Why: In the lifecycle of a component, React re-renders the component when an update is made. When React checks for any changes in a component, it may detect an unintended or unexpected change due to how JavaScript handles equality and shallow comparisons. This change in the React application will cause it to re-render unnecessarily. Additionally, if that re-rendering is an expensive operation, like a long for loop , it can hurt performance. Expensive operations can be costly in either time, memory, or processing. When: Optimal if the wrapped function is large and expensive.

    **How: **
    

    Memoization is an optimization technique which passes a complex function to be memoized. In memoization, the result is “remembered” when the same parameters are passed-in subsequently.

    const memoizedValue = React.useMemo(() => computeExpensiveValue(a, b), [a, b]);
    

    useMemo takes in a function and an array of dependencies. The dependency’s list are the elements useMemo watches: if there are no changes, the function result will stay the same. Otherwise, it will re-run the function. If they don’t change, it doesn’t matter if our entire component re-renders, the function won’t re-run but instead return the stored result.

  20. Question 14
    Senior

    Why would you need to bind event handlers to this ?

    • React
    Reveal answer

    Binding is not something that is specifc to React, but rather how this works in Javascript. When you define a component using an ES6 class, a common pattern is for an event handler to be a method on the class. In JavaScript, class methods are not bound by default. If you forget to bind this.someEventHandler and pass it to onChange , this will be undefined when the function is actually called. Generally, if you refer to a method without () after it, such as onChange={this.someEventHandler} , you should bind that method.

  21. Question 15
    Senior

    When to use useCallback , useMemo and useEffect ?

    • React React Hooks
    Reveal answer

    useEffect - It's the alternative for the class component lifecycle methods componentDidMount , componentWillUnmount , componentDidUpdate , etc. You can also use it to create a side effect when dependencies change, i.e. "If some variable changes, do this". useCallback - On every render, everything that's inside a functional component will run again. If a child component has a dependency on a function from the parent component, the child will re-render every time the parent re-renders even if that function "doesn't change" (the reference changes, but what the function does won't). It's used for optimization by avoiding unnecessary renders from the child, making the function change the reference only when dependencies change. You should use it when a function is a dependency of a side effect e.g. useEffect . useMemo - It will run on every render, but with cached values. It will only use new values when certain dependencies change. It's used for optimization when you have expensive computations.

  22. Question 15
    Senior

    What's a Pure Functional Component in React?

    • React
    Reveal answer

    A function is said to be pure if: Its return value is only determined by its input values Its return value is always the same for the same input values A React component is considered pure if it renders the same output for the same state and props. With React.memo() , you can create memoized functional components that bail out of rendering on unnecessary updates using shallow comparison of props.

  23. Question 16
    Senior

    Can you do Components Inheritance in React?

    • React
    Reveal answer

    The React Team has’t found any use cases where we would recommend creating component inheritance hierarchies. Props and composition give you all the flexibility you need to customize a component’s look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions. If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.

  24. Question 16
    Senior

    What is the second argument that can optionally be passed to setState and what is its purpose?

    • React
    Reveal answer

    A callback function which will be invoked when setState has finished and the component is re-rendered. Something that’s not spoken of a lot is that setState is asynchronous, which is why it takes in a second callback function. Typically it’s best to use another lifecycle method rather than relying on this callback function, but it’s good to know it exists. this.setState(

    { username: 'tylermcginnis33' },
    () => console.log('setState has finished and the component has re-rendered.')
    )
    
  25. Question 17
    Senior

    What is difference between Incremental DOM and Virtual DOM?

    • Angular React
    Reveal answer

    Incremental DOM is a library for building up DOM trees and updating them in-place when data changes. It differs from the established virtual DOM approach in that no intermediate tree is created (the existing tree is mutated in-place). This approach significantly reduces memory allocation and GC thrashing for incremental updates to the DOM tree therefore increasing performance significantly in some cases. Virtual DOM compares (diff) a new entire virtual DOM with the previous virtual DOM for changes then applies those changes to the actual DOM. - This approach creates a new virtual DOM to determine the

    changes (memory heavy). Has a big memory footprint because it needs headroom for changes that "might"
    

    happen to the virtual DOM.

  26. Question 18
    Senior

    Describe how events are handled in React

    • React
    Reveal answer

    In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent , which is React’s cross-browser wrapper around the browser’s native event. These synthetic events have the same interface as native events you’re used to, except they work identically across all browsers. What’s mildly interesting is that React doesn’t actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn’t need to worry about keeping track of event listeners when updating the DOM.

  27. Question 19
    Senior

    When would you use flushSync in ReactJS?

    • React React Hooks
    Reveal answer

    React 18 adds out-of-the-box performance improvements by doing more batching (automated) by default. Batching is when React groups multiple state updates into a single re-render for better performance. To opt-out of automatic batching, you can use flushSync so your component will be re-rendered after each state update. You might need it when for example some code may depend on reading something from the DOM immediately after a state change. Consider with automated batching:

    function handleClick() {
      setCount(c => c + 1);
      setFlag(f => !f);
      // React will only re-render once at the end (that's batching!)
    }
    

    Consider with flushSync :

    import { flushSync } from 'react-dom';
    function handleClick() {
      flushSync(() => {
        setCounter(c => c + 1);
      });
    // React has updated the DOM by now
    flushSync(() => {
      setFlag(f => !f);
    });
    // React has updated the DOM by now
    }
    
  28. Question 19
    Senior

    Why doesn't this.props.children.map work?

    • React
    Reveal answer

    this.props.children is an opaque data structure. It can be either an array or a single element. In your case, this.props.children is probably a single element, which is why the .map() method is undefined. You should use the React.Children API when manipulating the children prop.

  29. Question 20
    Senior

    When shall we use useReducer hook in ReactJS?

    • React React Hooks
    Reveal answer

    useReducer is an alternative to useState . useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. An example will be a list of items, where you need to add, update and remove items in the state, Here you might have noticed that the state management logic takes a good part of the component body. useReducer helps to separate the concerns of rendering vs a concern of state management. useReducer also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

    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}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      </>
    );
    }
    

    React guarantees that dispatch function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list. https://dmitripavlutin.com/5c33affee33e7c40e73028fb48a8367b/diagram.svg

  30. Question 20
    Senior

    Describe Flux vs MVC?

    • React ASP.NET MVC
    Reveal answer

    Traditional MVC patterns have worked well for separating the concerns of data (Model), UI (View) and logic (Controller) — but MVC architectures frequently encounter two main problems: Poorly defined data flow: The cascading updates which occur across views often lead to a tangled web of events which is difficult to debug. Lack of data integrity: Model data can be mutated from anywhere, yielding unpredictable results across the UI. With the Flux pattern complex UIs no longer suffer from cascading updates; any given React component will be able to reconstruct its state based on the data provided by the store. The Flux pattern also enforces data integrity by restricting direct access to the shared data.

Expert questions

10 questions
  1. Question 1
    Expert

    What is a Pure Function?

    • React
    Reveal answer

    A Pure function is a function that doesn't depend on and **doesn't modify the states **of variables out of its scope. Essentially, this means that a pure function will always return the same result given same parameters.

  2. Question 2
    Expert

    Explain some difference between Flux and AngularJS (1.x) approach

    • React
    Reveal answer

    UI components in AngularJS typically rely on some internal $scope to store their data. This data can be directly mutated from within the UI component or anything given access to $scope — a risky situation for any part of the component or greater application which relies on that data. By contrast, the Flux pattern encourages the use of immutable data. Because the store is the central authority on all data, any mutations to that data must occur within the store. The risk of data pollution is greatly reduced.

  3. Question 3
    Expert

    What is React Fiber?

    • React
    Reveal answer

    React Fiber is an ongoing reimplementation of React's core algorithm. The main difference between react and react fiber are these new features :-

    1. Incremental Rendering :- React v16.0 includes a completely rewritten server renderer. It’s really fast. It supports streaming, so you can start sending bytes to the client faster
    2. Handle errors in the render API : To make class component an error boundary we define a new lifecycle method called componentDidCatch(error, info).
    3. Return multiple elements from render : With this new feature in React v16.0 now we can also return an array of elements, and string from component’s render method.
    4. Portals : Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
    5. Fragments : A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.
  4. Question 4
    Expert

    How does React renderer work exactly when we call setState ?

    • React
    Reveal answer

    There are two steps of what we may call render :

    1. Virtual DOM render: when render method is called it returns a new virtual dom structure of the component. This render method is called always when you call setState() , because shouldComponentUpdate always returns true by default. So, by default, there is no optimisation here in React.
    2. Native DOM render: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.
  5. Question 5
    Expert

    What is the key architectural difference between a JavaScript library such as React and a JavaScript framework such as Angular?

    • React
    Reveal answer

    React enables developers to render a user interface. To create a full front-end application, developers need other pieces, such as state management tools like Redux. Like React, Angular enables developers to render a user interface, but it is a “batteries included” framework that includes prescriptive, opinionated solutions to common requirements like state management. While there are many other considerations when comparing React and Angular specifically, this key architectural difference means that: Using a library such as React can give a project a greater ability to evolve parts of the system—again for example, state management—over time, when new solutions are created by the open source community. Using a framework such as Angular can make it easier for developers to get started and can also simplify maintenance.

  6. Question 6
    Expert

    How to avoid the need for binding in React?

    • React
    Reveal answer

    There are several common approaches used to avoid methods binding in React:

    1. Define Your Event Handler as an Inline Arrow Function
    class SubmitButton extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isFormSubmitted: false
        };
    }
    render() {
      return (
      <button onClick={() => {
          this.setState({ isFormSubmitted: true });
        }}>Submit</button>
    )
    
    }
    }
    
    1. Define Your Event Handler as an Arrow Function Assigned to a Class Field
    class SubmitButton extends React.Component {
      state = {
        isFormSubmitted: false
      }
    handleSubmit = () => {
      this.setState({
        isFormSubmitted: true
      });
    }
    render() {
      return (
      <button onClick={this.handleSubmit}>Submit</button>
    )
    }
    }
    
    1. Use a Function Component with Hooks
    const SubmitButton = () => {
      const [isFormSubmitted, setIsFormSubmitted] = useState(false);
      return (
      <button onClick={() => {
          setIsFormSubmitted(true);
        }}>Submit</button>
    )
    };
    
  7. Question 8
    Expert

    How to use React.memo() ?

    • React
    Reveal answer

    With React.memo() , you can create memoized functional components that bail out of rendering on unnecessary updates using shallow comparison of props. Using the new React.memo() API, the functional component can be wrapped as follows:

    import React, { memo } from 'react';
    function PercentageStat({ label, score = 0, total = Math.max(1, score) }) {
      return (
      <div>
      <h6>{ label }</h6>
      <span>{ Math.round(score / total * 100) }%</span>
      </div>
    )
    }// Wrap component using `React.memo()`
    export default memo(PercentageStat);
    
  8. Question 9
    Expert

    What is a Pure Function?

    • React
    Reveal answer

    A Pure function is a function that doesn't depend on and **doesn't modify the states **of variables out of its scope. Essentially, this means that a pure function will always return the same result given same parameters.

  9. Question 9
    Expert

    Can a custom React hook return JSX?

    • React React Hooks
    Reveal answer

    While there is no hardcore restriction on how you should define custom hooks and what logic should contain, it's an anti-pattern to write hooks that return JSX. There are a few downsides to using hooks to return JSX When you write a hook that returns JSX component, you are essentially defining the component within the functional component, so on each and every re-render you will be creating a new instance of the component. This will lead to the component being unmounted and mounted again. This is bad for performance and also buggy if you have stateful login within the component as the state will get reset with every re-render of the parent By defining a JSX component within the hook, you are taking away the option of lazy loading your component if the need be. Any performance optimization to the component will require you to make use of useMemo which doesn't give you the flexibility of a custom comparator function like React.memo() The benefit on the other hand is that you have control over the state of the component in the parent. However, you can still implement the same logic by using a controlled component approach

  10. Question 10
    Expert

    What is the order of useInsertionEffect , useEffect and useLayoutEffect hooks at component generation ?

    • React
    Reveal answer

    useInsertionEffect It fires synchronously before all DOM mutations. Use this to inject styles into the DOM before reading layout in useLayoutEffect . So it runs before useLayoutEffect . useLayoutEffect It fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re- render. useEffect It will run after the render is committed to the screen. So it runs after useLayoutEffect . Therefore the order of running is:

    1. useInsertionEffect
    2. useLayoutEffect
    3. useEffect