React Interview Questions

¡Supera tus tareas y exámenes ahora con Quizwiz!

List down the components of Redux

1. Action - object that describes what happened. 2. Reducer - place to determine how the state will change. 3. Store - State / Object tree of the entire application is saved in the Store. 4. View - Displays the data provided by the Store.

Controlled Components

1. Do not maintain their own state. 2. Data is controlled by parent component. 3. They take in the current values through props and then notify the changes via callbacks.

Advantages of React (5)

1. Increases Application Performance 2. Can be used conveniently on the client as well as server side. 3. Code readability increases because of JSX. 4. React is easy to integrate with other frameworks. 5. Writing UI test cases becomes extremely easy.

What are the different phases of React component's lifecycle?

1. Initial Rendering Phase: This phase is when the component is about to state its life journey and make its way to the DOM. 2. Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase. 3. Unmounting Phase: This is the final phase of a component's life cycle in which the component is destroyed and removed from the DOM.

Limitations of React (4)

1. Just a library 2. Very large and hard to understand 3. It can be difficult for novice programmers to understand. 4. Coding gets complex as it uses inline templating and JSX.

Uncontrolled Components

1. Maintain their own state 2. Data is controlled by the DOM. 3. Refs are used to get their current values.

React Elements vs React Components

A React component is a function or a class which optionally accepts input and returns a React element (via JSX which gets transpiled to a createElement invocation)

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

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.

What is the significance of Store in Redux?

A store is a JS object which can hold the application's state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

What does shouldComponentUpdate do and why is it important?

Above we talked about reconciliation and what React does when setState is called. What shouldComponentUpdate does it it's a lifecycle method that allows us to opt out of this reconciliation process for certain components (and their child components). Why would we ever want to do this? As mentioned above, "The end goal of reconciliation is to, in the most efficient way possible, update the UI based on new state". 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.

How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator.

What are Higher Order Components.

Advanced way of reusing the component logic. Basically, it's a pattern that is derived from React's compositional nature. HOC are custom components which wraps another component within it. They can accept any dynamically provided child component but they won't modify or copy any behavior from their input components. You can say that HOC are pure components.

Why is the switch keyword used in React Router v4?

Although a <div> is used to encapsulate multiple routes inside the Router. The switch keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route.

What is an arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called 'fat arrow' functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions. //General way render() { return( <MyInput onChange={this.handleChange.bind(this) } /> ); } //With Arrow Function render() { return( <MyInput onChange={ (e) => this.handleOnChange(e) } /> ); }

Why can't browsers read JSX?

Browsers can read JS objects but JSX is not a regular JS object. We need to transform the JSX file into a JS object using JSX transformers like Babel and then pass it to the browser.

What is React Router?

Built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that's being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web apps.

componentWillUnmount()

Called after the component is unmounted from the DOM. It is used to clear up the memory spaces

componentDidUpdate()

Called immediately after rendering takes place.

What do you understand from "In React, everything is a component."

Components are the building blocks of a React application's UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

Differentiate between states and props.

Conditions, State, Props 1. Receive initial value from parent 2. Parent component can change value 3. Set default values inside component 4. Changes inside component 5. Set initial value for child components 6. Changes inside child components.

What were the major problems with MVC?

DOM manipulation was expensive. Applications were slow and inefficient. There was huge memory wastage. Complicated model was created around models and views.

Explain the purpose of render() in React.

Each React component must have a render() mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>, <div> etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

What are refs and why are they important.

Escape hatch which allows 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.

What is an event in React?

Events are triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like: i. Events are named using camel case instead of just using the lowercase. ii. Events are passed as functions instead of strings.

componentWillMount()

Executed just before rendering takes place both on the client as well as server side.

componentDidMount()

Executed on the client side only after the first render

How is Redux different from Flux?

Flux - The store contains state and change logic React - Store and change logic are separate F - Multiple store R - Only one store F - All stores are disconnected and flat R - Single store with hierarchical reducers F - Singleton dispatcher R - No concept of dispatcher F - React components subscribe to the store R - Container components utilize connect F - State is mutable R - State is immutable

Explain Flux

Flux is an architectural pattern which enforces the unidirectional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

What can you do with HOC?

HOC can be used for many tasks like: Code reuse, logic, and bootstrap abstraction Render High Jacking State abstraction and manipulation Props manipulation

When would you use a Class Component over a Functional Component?

If component has state or a lifecycle method, use a class component. Otherwise use a functional component.

What is Children?

In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed to components automatically as a special prop: props.children. 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.

Describe how events are handled in React.

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.

In which lifecycle event do you make AJAX requests and why?

In the componentDidMount lifecycle event. 1. Fiber, the new React reconciliation algorithm, has the ability to start and stop rendering as needed for performance benefits. One of the trade-offs of this is that componentWillMount, the other lifecycle event where it might make sense to make an AJAX request, will be non-deterministic. What this means is that React may start calling componentWillMount at various times whenever it feels like it needs to. This would obviously be a bad formula for AJAX requests. 2. You cannot guarantee the AJAX request won't resolve before the component mounts. If it did, that would mean that you'd be trying to setState on an unmounted component, which not only won't work, but React will yell at you for. Doing AJAX in componentDidMount will guarantee that there's a component to update.

componentWillReceiveProps()

Invoked as soon as the props are received from the parent class and before another render is called.

What is Redux?

It is a predictable state container for JS applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

What is JSX?

JSX is shorthand for JS XML. Makes it really easy to understand.

What is the significance of keys in React?

Keys are used for iding unique Virtual Dom elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application's performance.

Why would you use React.Children.map(props.children, () => ) instead of props.children.map(() => )

Not guaranteed that props.children will be an array. Inside of Parent if we were to try to map over children using props.children.map it would throw an error because props.children is an object, not an array. React only makes props.children an array if there are more than one child elements, like this Inside of Parent if we were to try to map over children using props.children.map it would throw an error because props.children is an object, not an array. React only makes props.children an array if there are more than one child elements, like this

What is wrong with this code? this.setState((prevState, props) => { return { streak: prevState.streak + props.count } })

Nothing is wrong with it 🙂. It's rarely used and not well known, but you can also pass a function to setState that receives the previous state and props and returns a new state, just as we're doing above. And not only is nothing wrong with it, but it's also actively recommended if you're setting state based on previous state.

What are the advantages of Redux?

Predictability of outcome Maintainability - Code becomes easier to maintain with a predictable outcome and strict structure. Server Side Rendering - Just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance. Developer tools Community - Huge community Easy of testing because small, pure, and isolated Organization - Redux is precise about how code should be organized

What are Pure Components?

Pure components are the simplest and fastest components which can be written. They can replace any component which only has a render(). These components enhance the simplicity of the code and performance of the application.

React vs Angular

React Only the view SSR Virtual DOM One way data Compile time debugging Facebook Angular MVC Client Side rendering Real DOM Two way data binding Run time debugging Google

How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements cannot directly update their state and their submission is handled by a JS function. This function has full access to the data that is entered by the user into a form. handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleSubmit} /> </label> <input type="submit" value="Submit" /> </form> ); }

What is React?

React is a frontend JS library developed by FB in 2011. It is component based which helps in building reusable UI components.

Real DOM vs Virtual DOM

Real DOM 1. Slow to update 2. Directly update HTML 3. Creates new DOM if element updates. 4. DOM manipulation is expensive 5. Memory Waste Virtual DOM 1. Updates faster 2. Cannot directly update HTML 3. Updates the JSX is element updates 4. DOM manipulation is easy 5. No memory wastage.

Explain the role of Reducer

Reducers are pure functions which specify how the application's state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

What is Redux Thunk used for?

Redux thunk is middleware that allows you to write action creators that return a function instead of an action. The thunk can then be used to delay the dispatch of an action if a certain condition is met. This allows you to handle the asyncronous dispatching of actions.

What do you understand by Single Source of Truth?

Redux uses the Store for storing the application's entire state in one place. So all the component's state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

What do you understand by refs in React?

Refs it the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

shouldComponentUpdate()

Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.

Why do we need a Router in React?

Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any 'route' defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes which each leading to us a unique view.

What is Props?

Shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components through out the application.

Stateful vs Stateless Components

Stateful Component Stateless Component 1. Stores info about component's state change in memory 1. Calculates the internal state of the components 2. Have authority to change state 2. Do not have the authority to change state 3. Contains the knowledge of past, current and possible future changes in state 3. Contains no knowledge of past, current and possible future state changes 4. Stateless components notify them about the requirement of the state change, then they send down the props to them. 4. They receive the props from the Stateful components and treat them as callback functions.

What is state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser's native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

List down the advantages of React Router

The API is All About Components. A Router can be visualized as a single root component. No need to set the history value, all we need to do is wrap our routes within the Browser Router component.

How do you tell React to build in Production mode and what will that do?

Typically you'd use Webpack's DefinePlugin method to set NODE_ENV to production. This will strip out things like propType validation and extra warnings. On top of that, it's also a good idea to minify your code because React uses Uglify's dead-code elimination to strip out development only code and comments, which will drastically reduce the size of your bundle.

Why would you eject create react app?

Until you eject you are unable to configure webpack or babel presets.

Features of React

Virtual DOM Server Side Rendering Unidirectional Data Flow

Explain Virtual DOM

Virtual DOM is a lightweight JS object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React's render function creates a node tree out of the React components. It then updates the tree in response to the mutations in the data. Real DOM will be updated with only the things that have changed.

How do you make React code modular?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

List some of the cases when you should use Refs.

When you need to manage focus, select text, or media playback. To trigger imperative animations. Integrate with third part DOM libraries.

componentWillUpdate()

called just before rendering takes place in the DOM

How do you create an event in React?

class Display extends React.Component({ show(evt) { // code }, render() { // Render the div with an onClick prop (value is a function) return ( <div onClick={this.show}>Click Me!</div> ); } });

How can you embed two or more components into one?

class MyComponent extends React.Component{ render(){ return( <div> <h1>Hello</h1> <Header/> </div> ); } } class Header extends React.Component{ render(){ return <h1>Header Component</h1> }; } ReactDOM.render( <MyComponent/>, document.getElementById('content') );

What is the difference between createElement and cloneElement?

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

What are the three principles that Redux follows?

i. Single source of truth. The state of the entire application is stored in an object/state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application. ii. State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. iii. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depend solely on the values of their arguments.

How different is React's ES6 syntax when compared to ES5?

require vs import export vs exports component and function props state

How can you update the state of a component?

this.setState()


Conjuntos de estudio relacionados

web fundamentals 1, web fundamentals 2, web fundamentals 3

View Set

GSBA544 - A Firm In A Global Economy

View Set

ACCY 1 LS: Chapter 8. Current Liabilities

View Set