Before moving to questions, It is recommended to go through https://www.w3schools.com/react/
What is React?
React is an open-source front-end JavaScript library that is used for building user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook's News Feed in 2011 and on Instagram in 2012.
What are the major features of React?
The major features of React are:
- It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive.
- Supports server-side rendering.
- Follows Unidirectional data flow or data binding.
- Uses reusable/composable UI components to develop the view.
- Allows you to use 3rd party libraries
- Time-Saving
- Faster Development
- Simplicity and Composable
What are the advantages of React?
Below are the list of main advantages of React,
- Increases the application's performance with Virtual DOM.
- JSX makes code easy to read and write.
- It renders both on client and server side (SSR).
- Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
- Easy to write unit and integration tests with tools such as Jest.
What are the limitations of React?
Apart from the advantages, there are few limitations of React too,
- React is just a view library, not a full framework.
- There is a learning curve for beginners who are new to web development.
- Integrating React into a traditional MVC framework requires some additional configuration.
- The code complexity increases with inline templating and JSX.
- Too many smaller components leading to over engineering or boilerplate.
What is CRA and its benefits?
The create-react-app CLI tool allows you to quickly create & run React applications with no configuration step.
Let's create Todo App using CRA:
# Installation
$ npm install -g create-react-app
# Create new project
$ create-react-app todo-app
$ cd todo-app
# Build, test and run
$ npm run build
$ npm run test
$ npm start
What is the difference between React and Angular?
Let's see the difference between React and Angular in a table format.
React | Angular |
---|
React is a library and has only the View layer | Angular is a framework and has complete MVC functionality |
React handles rendering on the server side | AngularJS renders only on the client side but Angular 2 and above renders on the server side |
React uses JSX that looks like HTML in JS which can be confusing | Angular follows the template approach for HTML, which makes code shorter and easy to understand |
React Native, which is a React type to build mobile applications are faster and more stable | Ionic, Angular's mobile native app is relatively less stable and slower |
In React, data flows only in one way and hence debugging is easy | In Angular, data flows both way i.e it has two-way data binding between children and parent and hence debugging is often difficult |
What is Babel?
Babel is a JavaScript compiler that can translate markup or programming languages into JavaScript. With Babel, you can use the newest features of JavaScript (ES6 - ECMAScript 2015). Babel is available for different conversions. React uses Babel to convert JSX into JavaScript.
Please note that <script type="text/babel"> is needed for using Babel.
What is JSX?
JSX stands for JavaScript XML. JSX is an XML/HTML like extension to JavaScript. It is the combination of JavaScript and Html.
Example: const element = <h1>Hello World!</h1>
Props in React
Props, short for Properties in React Props, short for properties, allow the user to pass arguments or data to components. These props help make the components more dynamic. Props in a component are read-only and cannot be changed. They are data passed down from a parent component to a child component.
State in React
A state is an object that stores properties values for those attributed to a component that could change over some time.
- A state can be changed as a result of a user's action or changes in the network.
- React re-renders the component to the browser whenever the state of an object changes.
- setState() is used to alter the state object's value.
- The setState() function merges the new and prior states shallowly
Props
|
State
|
Props
are used to send data and event handlers to a component's children.
|
The data
of the components that must be presented to it store the view in the state.
|
Props
are immutable — they can't be modified after they've been set.
|
The data
is stored in the state, which might change over time.
|
Both
functional and class components can benefit from the use of props.
|
Only
class components can use the state.
|
The
parent component sets props for the children components.
|
Event
handlers are typically responsible for updating the state.
|
Why should we not update the state directly?
If you try to update the state directly then it won't re-render the component.
//Wrong
this.state.message = 'Hello world'
Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.
//Correct
this.setState({ message: 'Hello World' })
Note: You can directly assign to the state object either in constructor or using latest javascript's class field declaration syntax.
What is useState() in React?
The useState() is a built-in React Hook that allows you for having state variables in functional components. It should be used when the DOM has something that is dynamically manipulating/controlling.
In the below-given example code, The useState(0) will return a tuple where the count is the first parameter that represents the counter’s current state and the second parameter setCounter method will allow us to update the state of the counter.
...
const [count, setCounter] = useState(0);
const [otherStuffs, setOtherStuffs] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setOtherStuffs(...);
...
};
We can make use of setCounter() method for updating the state of count anywhere. In this example, we are using setCounter() inside the setCount function where various other things can also be done. The idea with the usage of hooks is that we will be able to keep our code more functional and avoid class-based components if they are not required.
What is the purpose of callback function as an argument of setState()?
The callback function is invoked when setState finished and the component gets rendered. Since setState() is asynchronous the callback function is used for any post action.
Note: It is recommended to use lifecycle method rather than this callback function.
setState({ name: 'John' }, () =>
console.log('The name has updated and component re-rendered'))
What is the virtual DOM?
React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, the virtual DOM changes only that object in the real DOM, rather than updating all the objects.
Why use React instead of other frameworks, like Angular?
- Easy creation of dynamic applications
- Improved performance
- Reusable components
- Unidirectional data flow
What is an event in React?
An event is an action that a user or system may trigger, such as pressing a key, a mouse click, etc.
React events are named using camelCase, rather than lowercase in HTML.
With JSX, you pass a function as the event handler, rather than a string in HTML.
<Button onPress={lightItUp} />
How do you create an event in React?
A React event can be created by doing the following:
import React from 'react';
import './NewExpense.css';
import ExpenseForm from './ExpenseForm';
const NewExpense= (props) => {
const saveExpenseDatahandler=(enteretExpenseData) => {
};
return (
<div className='new-expense'>
<ExpenseForm onSaveExpenseData={saveExpenseDatahandler}>
</ExpenseForm>
</div>
);
}
export default NewExpense;
Why is there a need for using keys in Lists?
A key is a unique identifier and it is used to identify which items have changed, updated or deleted from the lists.
const ids = [1,2,3,4,5];
const listElements = ids.map((id)=>{
return(
<li key={id.toString()}>
{id}
</li>
)
})
Importance of keys -
- Keys help react identify which elements were added, changed or removed.
- Keys should be given to array elements for providing a unique identity for each element.
- Without keys, React does not understand the order or uniqueness of each element.
- With keys, React has an idea of which particular element was deleted, edited, and added.
- Keys are generally used for displaying a list of data coming from an API.
How is React different from Angular?
|
Angular
|
React
|
Author
|
Google
|
Facebook
|
Architecture
|
Complete MVC
|
View layer of MVC
|
DOM
|
Real DOM
|
Virtual DOM
|
Data-Binding
|
Bi-directional
|
Uni-directional
|
Rendering
|
Client-Side
|
Server-Side
|
Performance
|
Comparatively slow
|
Faster due to Virtual DOM
|
ReactJS Interview Questions on Components
Here are some React Interview Questions on components.
What are the components in React?
Components are the building blocks of any React application, and a single app usually consists of multiple components. A component is essentially a piece of the user interface. It splits the user interface into independent, reusable parts that can be processed separately.
There are two types of components in React:
- Functional component
- Class component
What are the differences between functional and class components?
Before the introduction of Hooks in React, functional components were called stateless components and were behind class components on a feature basis. After the introduction of Hooks, functional components are equivalent to class components.
Although functional components are the new trend, the react team insists on keeping class components in React. Therefore, it is important to know how these components differ.
Functional Components: These types of components have no state of their own and only contain render methods, and therefore are also called stateless components. They may derive data from other components as props (properties).
Functional components use React hooks to handle state. It uses the useState hook to set the state of a variable inside the component. useState hook returns an array of two items, the first item contains the current state, and the second item is a function used to update the state.
function Greeting(props) {
return <h1>Welcome to {props.name}</h1>;
}
Class Components: These types of components can hold and manage their own state and have a separate render method to return JSX on the screen. They are also called Stateful components as they can have a state.
We cannot use React Hooks inside class components, therefore state handling is done very differently in a class component.
class Greeting extends React.Component {
constructor(props){
super(props);
this.state = {studentsCount : 0};
this.addStudent = this.addStudent.bind(this);
}
addStudent(){
this.setState((prevState)=>{
return {studentsCount: prevState.studentsCount++}
});
}
render(){
return(
<div>
<p>Number of students in class room: {this.state.studentsCount}</p>
<button onClick={this.addStudent}>Add Student</button>
</div>
)
}
}
In the code above, we see we are using this.state to add the variable studentsCount and setting the value to “0”.
For reading the state, we are using this.state.studentsCount.
For updating the state, we need to first bind the addStudent function to this. Only then, we will be able to use the setState function which is used to update the state.
When to use a Class Component over a Function Component?
If the component needs state or lifecycle methods then use class component otherwise use function component.
What are Pure Components?
React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.
What are the different phases of component lifecycle?
Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.
The three phases are: Mounting, Updating, and Unmounting
- Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.
- Updating: In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.
- Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.
It's worth mentioning that React internally has a concept of phases when applying changes to the DOM. They are separated as follows
- Render The component will render without any side effects. This applies to Pure components and in this phase, React can pause, abort, or restart the render.
- Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate().
- Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.
What are the lifecycle methods going to be deprecated in React v16?
The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering.
- componentWillMount()
- componentWillReceiveProps()
- componentWillUpdate()
Starting with React v16.3 these methods are aliased with UNSAFE_ prefix, and the unprefixed version will be removed in React v17.
What is the recommended ordering of methods in component class?
Recommended ordering of methods from mounting to render stage:
- static methods
- constructor()
- getChildContext()
- componentWillMount()
- componentDidMount()
- componentWillReceiveProps()
- shouldComponentUpdate()
- componentWillUpdate()
- componentDidUpdate()
- componentWillUnmount()
- click handlers or event handlers like onClickSubmit() or onChangeDescription()
- getter methods for render like getSelectReason() or getFooterContent()
- optional render methods like renderNavigation() or renderProfilePicture()
- render()
What is the use of render() in React?
It is required for each component to have a render() function. This function returns the HTML, which is to be displayed in the component.
If you need to render more than one element, all of the elements must be inside one parent tag like <div>, <form>.
What is a state in React?
The state is a built-in React object that is used to contain data or information about the component. The state in a component can change over time, and whenever it changes, the component re-renders.
The change in state can happen as a response to user action or system-generated events. It determines the behavior of the component and how it will render.
State is similar to props, but it is private and fully controlled by the component ,i.e., it is not accessible to any other component till the owner component decides to pass it.
How do you update the state of a component?
We can update the state of a component by using the built-in ‘setState()’ method:
What are props in React?
The props in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.
The main purpose of props is to provide different component functionalities such as:
- Passing custom data to the React component.
- Using through this.props.reactProp inside render() method of the component.
- Triggering state changes.
For example, consider we are creating an element with reactProp property as given below:
<Element reactProp = "1" />
This reactProp name will be considered as a property attached to the native props object of React which already exists on each component created with the help of React library: props.reactProp;
What are the differences between state and props?
|
State
|
Props
|
Use
|
Holds information about the
components
|
Allows to pass data from one component to other components as an
argument
|
Mutability
|
Is mutable
|
Are immutable
|
Read-Only
|
Can be changed
|
Are read-only
|
Child components
|
Child components cannot access
|
Child component can access
|
Stateless
components
|
Cannot have state
|
Can have props
|
What is a higher-order component in React?
A higher-order component acts as a container for other components. This helps to keep components simple and enables re-usability. They are generally used when multiple components have to use a common logic.
ReactJS Redux Interview Questions
What is Redux?
Redux is an open-source, JavaScript library used to manage the application state. React uses Redux to build the user interface. It is a predictable state container for JavaScript applications and is used for the entire application’s state management.
What are the components of Redux?
Store: Holds the state of the application.
Action: The source information for the store.
Reducer: Specifies how the application's state changes in response to actions sent to the store.
What is the Flux?
- Flux is the application architecture that Facebook uses for building web applications. It is a method of handling complex data inside a client-side application and manages how data flows in a React application.
- There is a single source of data (the store) and triggering certain actions is the only way way to update them. The actions call the dispatcher, and then the store is triggered and updated with their own data accordingly.
- When a dispatch has been triggered, and the store updates, it will emit a change event that the views can re-render accordingly.
How is Redux different from Flux?
Redux
|
Flux
|
Redux
is an open-source JavaScript library used to manage application State
|
Flux
is an architecture and not a framework or library
|
Store’s
state is immutable
|
Store’s
state is mutable
|
Can
only have a single-store
|
Can
have multiple stores
|
Uses
the concept of reducer
|
Uses
the concept of the dispatcher
|
ReactJS Styling Questions
How do you style React components?
There are several ways in which we can style React components:
- Inline Styling
- JavaScript Object
- CSS Stylesheet
Explain the use of CSS modules in React.
- The CSS module file is created with the .module.css extension.
- The CSS inside a module file is available only for the component that imported it, so there are no naming conflicts while styling the components.
What is children prop?
This props.children allow you to pass a component as data to other components, just like any other prop you use. Component tree put between component's opening and closing tag will be passed to that component as children prop.
There are several 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.
const MyDiv = React.createClass({
render: function() {
return <div>{this.props.children}</div>
}
})
ReactDOM.render(
<MyDiv>
<span>{'Hello'}</span>
<span>{'World'}</span>
</MyDiv>,
node
)
How to write comments in React?
The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.
Single-line comments:
<div>
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */}
{`Welcome ${user}, let's play React`}
</div>
Multi-line comments:
<div>
{/* Multi-line comments for more than
one line */}
{`Welcome ${user}, let's play React`}
</div>
What is the purpose of using super constructor with props argument?
A child class constructor cannot make use of this reference until the super() method has been called. The same applies to ES6 sub-classes as well. The main reason for 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: 'John', age: 42 }
}
}
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: 'John', age: 42 }
}
render() {
// no difference outside constructor
console.log(this.props) // prints { name: 'John', age: 42 }
}
}
The above code snippets reveals that this.props is different only within the constructor. It would be the same outside the constructor.
What is reconciliation?
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.
How to set state with a dynamic key name?
If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.
handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
What would be the common mistake of function being called every time the component renders?
You need to make sure that function is not being called while passing the function as a parameter.
render() {
// Wrong: 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: handleClick is passed as a reference!
return <button onClick={this.handleClick}>{'Click Me'}</button>
}
Why React uses className over class attribute?
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. Pass a string as the className prop.
render() {
return <span className={'menu navigation-menu'}>{'Menu'}</span>
}
What are fragments?
It's a 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>
)
}
Why fragments are better than container divs?
Below are the list of reasons,
- Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.
- Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
- The DOM Inspector is less cluttered.
What are stateless components?
If the behaviour of a component 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 function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.
What are stateful components?
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() {
// ...
}
}
How to apply validation on props in React?
When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact. The mandatory props are defined with isRequired.
The set of predefined prop types:
- PropTypes.number
- PropTypes.string
- PropTypes.array
- PropTypes.object
- PropTypes.func
- PropTypes.node
- PropTypes.element
- PropTypes.bool
- PropTypes.symbol
- PropTypes.any
We can define propTypes for User component as below:
import React from 'react'
import PropTypes from 'prop-types'
class User extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
)
}
}
What is the use of react-dom package?
The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:
- render()
- hydrate()
- unmountComponentAtNode()
- findDOMNode()
- createPortal()
What is the purpose of render method of react-dom?
This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.
ReactDOM.render(element, container, [callback])
If the optional callback is provided, it will be executed after the component is rendered or updated.
How to use styles in React?
The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')'
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>
}
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage).
How events are different in React?
Handling events in React elements has some syntactic differences:
- React event handlers are named using camelCase, rather than lowercase.
- With JSX you pass a function as the event handler, rather than a string.
What will happen if you use setState() in constructor?
When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get error like this: Can only update a mounted or mounting component. So we need to use this.state to initialize variables inside constructor.
How you implement Server Side Rendering or SSR?
React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.
import ReactDOMServer from 'react-dom/server'
import App from './App'
ReactDOMServer.renderToString(<App />)
This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response. On the client side, React detects the pre-rendered content and seamlessly picks up where it left off.
Why should component names start with capital letter?
If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.
class SomeComponent extends Component {
// Code goes here
}
You can define component class which name starts with lowercase letter, but when it's imported it should have capital letter. Here lowercase is fine:
class myComponent extends Component {
render() {
return <div />
}
}
export default myComponent
While when imported in another file it should start with capital letter:
import MyComponent from './myComponent'
Can you force a component to re-render without calling setState?
Yes
component.forceUpdate(callback)
How to conditionally apply class attributes?
You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.
<div className="btn-panel {this.props.visible ? 'show' : 'hidden'}"></div>
Instead you need to move curly braces outside (don't forget to include spaces between class names):
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}></div>
Template strings will also work:
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}></div>
What is the difference between React and ReactDOM?
The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().
What is the difference between setState() and replaceState() methods?
When you use setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().
How to listen to state changes?
The componentDidUpdate lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.
componentDidUpdate(object prevProps, object prevState)
Note: The previous releases of ReactJS also uses componentWillUpdate(object nextProps, object nextState) for state changes. It has been deprecated in latest releases.
Why you can't update props in React?
The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.
What are the possible ways of updating objects in state?
1- Calling setState() with an object to merge with state:
Using Object.assign() to create a copy of the object:
const user = Object.assign({}, this.state.user, { age: 42 })
this.setState({ user })
Using spread operator:
const user = { ...this.state.user, age: 42 }
this.setState({ user })
2- Calling setState() with a function:
this.setState(prevState => ({
user: {
...prevState.user,
age: 42
}
}))
How to make AJAX call and in which component lifecycle methods should I make an AJAX call?
You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.
For example, the employees list fetched from API and set local state:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
employees: [],
error: null
}
}
componentDidMount() {
fetch('https://api.example.com/items')
.then(res => res.json())
.then(
(result) => {
this.setState({
employees: result.employees
})
},
(error) => {
this.setState({ error })
}
)
}
render() {
const { error, employees } = this.state
if (error) {
return <div>Error: {error.message}</div>;
} else {
return (
<ul>
{employees.map(employee => (
<li key={employee.name}>
{employee.name}-{employee.experience}
</li>
))}
</ul>
)
}
}
}
What is React Router?
React Router is a routing library built on top of React, which is used to create routes in a React application.
React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native. https://reactrouter.com/en/
Why do we need to React Router?
It maintains consistent structure and behavior and is used to develop single-page web applications.
Enables multiple views in a single application by defining multiple routes in the React application.
How do you implement React routing?
...
How to get query parameters in React Router v4?
The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementation. So the decision has been given to users to choose the implementation they like. The recommended approach is to use query strings library.
const queryString = require('query-string');
const parsed = queryString.parse(props.location.search);
You can also use URLSearchParams if you want something native:
const params = new URLSearchParams(props.location.search)
const foo = params.get('name')
Why you get "Router may have only one child element" warning?
You have to wrap your Route's in a <Switch> block because <Switch> is unique in that it renders a route exclusively.
At first you need to add Switch to your imports:
import { Switch, Router, Route } from 'react-router'
Then define the routes within <Switch> block:
<Router>
<Switch>
<Route {/* ... */} />
<Route {/* ... */} />
</Switch>
</Router>
How to implement default or NotFound page?
A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as below
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/user" component={User}/>
<Route component={NotFound} />
</Switch>
How to pass data between sibling components using React router?
Passing data between sibling components of React is possible using React Router with the help of history.push and match.params.
In the code given below, we have a Parent component AppDemo.js and have two Child Components HomePage and AboutPage. Everything is kept inside a Router by using React-router Route. It is also having a route for /about/{params} where we will pass the data.
import React, { Component } from ‘react’;
class AppDemo extends Component {
render() {
return (
<Router>
<div className="AppDemo">
<ul>
<li>
<NavLink to="/" activeStyle={{ color:'blue' }}>Home</NavLink>
</li>
<li>
<NavLink to="/about" activeStyle={{ color:'blue' }}>About
</NavLink>
</li>
</ul>
<Route path="/about/:aboutId" component={AboutPage} />
<Route path="/about" component={AboutPage} />
<Route path="/" component={HomePage} />
</div>
</Router>
);
}
}
export default AppDemo;
The HomePage is a functional component with a button. On button click, we are using props.history.push(‘/about/’ + data) to programmatically navigate into /about/data.
export default function HomePage(props) {
const handleClick = (data) => {
props.history.push('/about/' + data);
}
return (
<div>
<button onClick={() => handleClick('DemoButton')}>To About</button>
</div>
)
}
Also, the functional component AboutPage will obtain the data passed by props.match.params.aboutId.
export default function AboutPage(props) {
if(!props.match.params.aboutId) {
return <div>No Data Yet</div>
}
return (
<div>
{`Data obtained from HomePage is ${props.match.params.aboutId}`}
</div>
)
}
After button click in the HomePage the page will look like below:
What is Jest?
Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing components.
Give a simple example of Jest test case
Let's write a test for a function that adds two numbers in sum.js file:
const sum = (a, b) => a + b
export default sum
Create a file named sum.test.js which contains actual test:
import sum from './sum'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3)
})
And then add the following section to your package.json:
{
"scripts": {
"test": "jest"
}
}
Finally, run yarn test or npm test and Jest will print a result:
$ npm test
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (2ms)
Explain about types of side effects in React component.
There are two types of side effects in React component. They are:
Effects without Cleanup: This side effect will be used in useEffect which does not restrict the browser from screen update. It also improves the responsiveness of an application. A few common examples are network requests, Logging, manual DOM mutations, etc.
Effects with Cleanup: Some of the Hook effects will require the cleanup after updating of DOM is done. For example, if you want to set up an external data source subscription, it requires cleaning up the memory else there might be a problem of memory leak. It is a known fact that React will carry out the cleanup of memory when the unmounting of components happens. But the effects will run for each render() method rather than for any specific method. Thus we can say that, before execution of the effects succeeding time the React will also cleanup effects from the preceding render.
What is prop drilling in React?
Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested. To pass data between such components, we pass props from a source component and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.
The disadvantage of using prop drilling is that the components that should otherwise be not aware of the data have access to the data.
Explain Strict Mode in React.
StrictMode is a tool added in version 16.3 of React to highlight potential problems in an application. It performs additional checks on the application.
function App() {
return (
<React.StrictMode>
<div classname="App">
<Header/>
<div>
Page Content
</div>
<Footer/>
</div>
</React.StrictMode>
);
}
To enable StrictMode, <React.StrictMode> tags need to be added inside the application:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
StrictMode currently helps with the following issues:
- Identifying components with unsafe lifecycle methods:
- Certain lifecycle methods are unsafe to use in asynchronous react applications. With the use of third-party libraries, it becomes difficult to ensure that certain lifecycle methods are not used.
- StrictMode helps in providing us with a warning if any of the class components use an unsafe lifecycle method.
- Warning about the usage of legacy string API:
- If one is using an older version of React, callback ref is the recommended way to manage refs instead of using the string refs. StrictMode gives a warning if we are using string refs to manage refs.
- Warning about the usage of findDOMNode:
- Previously, findDOMNode( ) method was used to search the tree of a DOM node. This method is deprecated in React. Hence, the StrictMode gives us a warning about the usage of this method.
- Warning about the usage of legacy context API (because the API is error-prone).
How to prevent re-renders in React?
- Reason for re-renders in React:
- Re-rendering of a component and its child components occur when props or the state of the component has been changed.
- Re-rendering components that are not updated, affects the performance of an application.
- How to prevent re-rendering:
Consider the following components:
class Parent extends React.Component {
state = { messageDisplayed: false };
componentDidMount() {
this.setState({ messageDisplayed: true });
}
render() {
console.log("Parent is getting rendered");
return (
<div className="App">
<Message />
</div>
);
}
}
class Message extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}
The Parent component is the parent component and the Message is the child component. Any change in the parent component will lead to re-rendering of the child component as well. To prevent the re-rendering of child components, we use the shouldComponentUpdate( ) method:
**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s a static component.
class Message extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
shouldComponentUpdate() {
console.log("Does not get rendered");
return false;
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}
As one can see in the code above, we have returned false from the shouldComponentUpdate( ) method, which prevents the child component from re-rendering.
Name a few techniques to optimize React app performance.
There are many ways through which one can optimize the performance of a React app, let’s have a look at some of them:
- Using useMemo()
- Using React.PureComponent
- Maintaining State Colocation
- Lazy Loading
How to pass data between react components?
How do we do this?
Consider the following Parent Component:
import ChildComponent from "./Child";
function ParentComponent(props) {
let [counter, setCounter] = useState(0);
let increment = () => setCounter(++counter);
return (
<div>
<button onClick={increment}>Increment Counter</button>
<ChildComponent counterValue={counter} />
</div>
);
}
As one can see in the code above, we are rendering the child component inside the parent component, by providing a prop called counterValue. The value of the counter is being passed from the parent to the child component.
We can use the data passed by the parent component in the following way:
function ChildComponent(props) {
return (
<div>
<p>Value of counter: {props.counterValue}</p>
</div>
);
}
We use the props.counterValue to display the data passed on by the parent component.
Child Component to Parent Component (using callbacks)
This one is a bit tricky. We follow the steps below:
- Create a callback in the parent component which takes in the data needed as a parameter.
- Pass this callback as a prop to the child component.
- Send data from the child component using the callback.
We are considering the same example above but in this case, we are going to pass the updated counterValue from child to parent.
Step1 and Step2: Create a callback in the parent component, pass this callback as a prop.
function ParentComponent(props) {
let [counter, setCounter] = useState(0);
let callback = valueFromChild => setCounter(valueFromChild);
return (
<div>
<p>Value of counter: {counter}</p>
<ChildComponent callbackFunc={callback} counterValue={counter} />
</div>
);
}
As one can see in the code above, we created a function called callback which takes in the data received from the child component as a parameter.
Next, we passed the function callback as a prop to the child component.
Step3: Pass data from the child to the parent component.
function ChildComponent(props) {
let childCounterValue = props.counterValue;
return (
<div>
<button onClick={() => props.callbackFunc(++childCounterValue)}>
Increment Counter
</button>
</div>
);
}
In the code above, we have used the props.counterValue and set it to a variable called childCounterValue.
Next, on button click, we pass the incremented childCounterValue to the props.callbackFunc.
This way, we can pass data from the child to the parent component.
What is Context?
React context helps you to pass data using the tree of react components. It helps you to share data globally between various react components.
Explain the meaning of Mounting and Demounting
The process of attaching the element to the DCOM is called mounting.
The process of detaching the element from the DCOM is called the demounting process.
Reference: https://www.simplilearn.com/, https://github.com/
0 comments:
Post a Comment