InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
How to perform automatic redirect after login? |
|
Answer» The REACT-router package will provide the component <Redirect> in React Router. Rendering of a <Redirect> component will navigate to a newer location. In the history stack, the current location will be overridden by the new location just like the server-side redirects. import React, { Component } from 'react'import { Redirect } from 'react-router'export default class LoginDemoComponent extends Component { render() { if (this.STATE.isLoggedIn === true) { return <Redirect to="/your/redirect/page" /> } else { return <div>{'Please complete login'}</div> } }}ConclusionReact has got more popularity among the top IT companies like Facebook, PayPal, Instagram, Uber, etc., around the world especially in India. Hooks is becoming a trend in the React community as it removes the state management complexities. This article includes the most frequently asked ReactJS and React Hooks interview questions and answers that will help you in interview preparations. Also, remember that your success during the interview is not all about your technical skills, it will also be based on your state of mind and the GOOD impression that you will make at first. All the best!! Useful References and Resources:
|
|
| 2. |
How to pass data between sibling components using React router? |
|
Answer» 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: |
|
| 3. |
How to re-render the view when the browser is resized? |
|
Answer» It is possible to listen to the resize EVENT in componentDidMount() and then update the width and HEIGHT dimensions. It requires the REMOVAL of the event listener in the componentWillUnmount() method. Using the below-given code, we can RENDER the view when the browser is resized. class WindowSizeDimensions extends React.Component { constructor(PROPS){ super(props); this.updateDimension = this.updateDimension.bind(this); } componentWillMount() { this.updateDimension() } componentDidMount() { window.addEventListener('resize', this.updateDimension) } componentWillUnmount() { window.removeEventListener('resize', this.updateDimension) } updateDimension() { this.setState({width: window.innerWidth, height: window.innerHeight}) } render() { return <span>{this.state.width} x {this.state.height}</span> }} |
|
| 4. |
How to create a switching component for displaying different pages? |
|
Answer» A SWITCHING component refers to a component that will RENDER one of the multiple components. We should use an object for mapping prop values to components. A below-given example will show you how to display different PAGES based on page prop using switching component: import HomePage from './HomePage'import AboutPage from './AboutPage'import FacilitiesPage from './FacilitiesPage'import ContactPage from './ContactPage'import HelpPage from './HelpPage'const PAGES = { home: HomePage, about: AboutPage, facilitiess: FacilitiesPage, contact: ContactPage help: HelpPage}const Page = (props) => { const Handler = PAGES[props.page] || HelpPage return <Handler {...props} />}// The PAGES object keys can be used in the prop TYPES for CATCHING errors during dev-time.Page.propTypes = { page: PropTypes.oneOf(Object.keys(PAGES)).isRequired} |
|
| 5. |
Explain how to create a simple React Hooks example program. |
|
Answer» I will assume that you are having some coding knowledge about JavaScript and have installed Node on your system for creating a below given React HOOK program. An installation of Node comes along with the command-line tools: npm and npx, where npm is useful to install the packages into a project and npx is useful in running commands of Node from the command line. The npx looks in the current project folder for checking whether a command has been installed there. When the command is not available on your computer, the npx will look in the npmjs.com repository, then the latest version of the command script will be loaded and will run without locally installing it. This feature is useful in creating a skeleton React application within a few key presses. Open the Terminal inside the folder of your choice, and run the following command: npx create-react-app react-items-with-hooksHere, the create-react-app is an app initializer created by Facebook, to help with the easy and quick creation of React application, providing options to customize it while creating the application? The above command will create a new folder named react-items-with-hooks and it will be initialized with a basic React application. Now, you will be able to open the project in your favourite IDE. You can see an src folder inside the project along with the main application component App.js. This file is having a single function App() which will return an element and it will make use of an extended JavaScript syntax(JSX) for defining the component. JSX will permit you for writing HTML-style template syntax directly into the JavaScript file. This mixture of JavaScript and HTML will be converted by React toolchain into pure JavaScript that will render the HTML element. It is possible to define your own React components by writing a function that will return a JSX element. You can try this by creating a new file src/SearchItem.jsand put the following CODE into it. import React from 'react';export function SearchItem() { return ( <div> <div className="search-input"> <input type="TEXT" placeholder="SearchItem"/> </div> <h1 className="h1">Search Results</h1> <div className="items"> <table> <thead> <tr> <th className="itemname-col">Item Name</th> <th className="price-col">Price</th> <th className="quantity-col">Quantity</th> </tr> </thead> <tbody></tbody> </table> </div> </div> );}This is all about how you can create a component. It will only display the empty table and doesn’t do anything. But you will be able to use the Search component in the application. Open the file src/App.js and add the import statement given below to the top of the file. import { SearchItem } from './SearchItem';Now, from the logo.svg, import will be removed and then contents of returned VALUE in the function App() will be replaced with the following code: <div className="App"> <header> Items with Hooks </header> <SearchItem/></div>You can notice that the element <SearchItem/> has been used just similar to an HTML element. The JSX syntax will enable for including the components in this approach directly within the JavaScript code. Your application can be tested by running the below-given command in your terminal. npm start This command will compile your application and open your default browser into http://localhost:4000. This command can be kept on running when code development is in progress to make SURE that the application is up-to-date, and also this browser page will be reloaded each time you modify and save the code. This application will work finely, but it doesn’t look nice as it doesn’t react to any input from the user. You can make it more interactive by adding a state with React Hooks, adding authentication, etc. |
|
| 6. |
Explain conditional rendering in React. |
|
Answer» Conditional rendering refers to the dynamic output of USER interface markups based on a condition state. It works in the same way as JavaScript CONDITIONS. Using conditional rendering, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on. There are different approaches for implementing conditional rendering in React. Some of them are:
|
|
| 7. |
Can React Hook replaces Redux? |
|
Answer» The React Hook cannot be considered as a replacement for Redux (It is an open-source, JavaScript library useful in managing the application state) when it COMES to the management of the global application state tree in large complex APPLICATIONS, even though the React will PROVIDE a useReducer hook that manages state transitions similar to Redux. Redux is very useful at a lower LEVEL of component hierarchy to handle the pieces of a state which are dependent on each other, instead of a declaration of multiple useState hooks. In commercial web applications which is larger, the complexity will be high, so using only React Hook may not be sufficient. Few developers will try to tackle the challenge with the HELP of React Hooks and others will combine React Hooks with the Redux. |
|
| 8. |
What is React Router? |
|
Answer» React Router REFERS to the standard library used for routing in React. It permits us for building a single-page web APPLICATION in React with navigation without even refreshing the page when the user navigates. It also allows to change the browser URL and will keep the user interface in sync with the URL. React Router will make use of the component structure for calling the components, using which appropriate information can be SHOWN. Since React is a component-based framework, it’s not necessary to include and use this package. Any other COMPATIBLE routing library would also work with React. The major components of React Router are given below:
|
|
| 9. |
Do Hooks cover all the functionalities provided by the classes? |
|
Answer» Our goal is for Hooks to cover all the functionalities for classes at its earliest. There are no Hook EQUIVALENTS for the following methods that are not INTRODUCED in Hooks yet:
Since it is an EARLY time for Hooks, few third-party libraries may not be compatible with Hooks at present, but they will be ADDED soon. |
|
| 10. |
How does the performance of using Hooks will differ in comparison with the classes? |
Answer»
|
|
| 11. |
Differentiate React Hooks vs Classes. |
||||||||||||
Answer»
|
|||||||||||||
| 12. |
Explain about types of Hooks in React. |
|
Answer» There are two types of Hooks in React. They are: 1. Built-in Hooks: The built-in Hooks are divided into 2 parts as given below:
2. Custom Hooks: A custom Hook is basically a function of JavaScript. The Custom Hook working is similar to a regular function. The “use” at the beginning of the Custom Hook Name is required for React to understand that this is a custom Hook and also it will describe that this specific function follows the rules of Hooks. Moreover, developing custom Hooks will enable you for extracting component logic from within reusable functions. |
|
| 13. |
Does React Hook work with static typing? |
|
Answer» Static TYPING refers to the process of code check during the time of compilation for ensuring all VARIABLES will be statically typed. React Hooks are FUNCTIONS that are designed to make SURE about all attributes must be statically typed. For enforcing stricter static typing within our code, we can make use of the React API with custom Hooks. |
|
| 14. |
What are the lifecycle methods of React? |
|
Answer» React lifecycle hooks will have the methods that will be automatically called at different phases in the component lifecycle and thus it provides GOOD control over what happens at the invoked point. It provides the power to effectively control and manipulate what goes on throughout the component lifecycle. For example, if you are developing the YouTube application, then the application will make use of a network for BUFFERING the videos and it consumes the power of the battery (assume only these two). After playing the video if the user switches to any other application, then you should make sure that the resources like network and battery are being used most efficiently. You can stop or pause the video buffering which in turn stops the battery and network usage when the user switches to another application after video play. So we can say that the developer will be able to produce a quality application with the help of lifecycle methods and it also helps developers to make sure to plan what and how to do it at different points of birth, growth, or death of user interfaces. The VARIOUS lifecycle methods are:
|
|
| 15. |
What are the different phases of the component lifecycle? |
|
Answer» There are four different phases in the LIFECYCLE of REACT component. They are:
|
|
| 16. |
What are Higher Order Components? |
|
Answer» Simply put, Higher-Order Component(HOC) is a function that takes in a component and returns a new component. When do we need a Higher Order Component? While developing React applications, we might develop components that are quite similar to each other with minute differences. In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY, therefore, we want an abstraction that allows us to define this logic in a single place and share it across components. HOC allows us to create that abstraction. Example of a HOC: Consider the following components having similar functionality. The following component displays the list of articles: // "GlobalDataSource" is some global DATA sourceclass ArticlesList extends React.Component { constructor(PROPS) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { articles: GlobalDataSource.getArticles(), }; } componentDidMount() { // Listens to the changes added GlobalDataSource.addChangeListener(this.handleChange); } componentWillUnmount() { // Listens to the changes removed GlobalDataSource.removeChangeListener(this.handleChange); } handleChange() { // States gets Update whenver data source changes this.setState({ articles: GlobalDataSource.getArticles(), }); } render() { return ( <div> {this.state.articles.map((article) => ( <ArticleData article={article} key={article.id} /> ))} </div> ); }}The following component displays the list of users: // "GlobalDataSource" is some global data sourceclass UsersList extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { users: GlobalDataSource.getUsers(), }; } componentDidMount() { // Listens to the changes added GlobalDataSource.addChangeListener(this.handleChange); } componentWillUnmount() { // Listens to the changes removed GlobalDataSource.removeChangeListener(this.handleChange); } handleChange() { // States gets Update whenver data source changes this.setState({ users: GlobalDataSource.getUsers(), }); } render() { return ( <div> {this.state.users.map((user) => ( <UserData user={user} key={user.id} /> ))} </div> ); }}Notice the above components, both have similar functionality but, they are calling DIFFERENT methods to an API endpoint. Let’s create a Higher Order Component to create an abstraction: // Higher Order Component which takes a component// as input and returns another component// "GlobalDataSource" is some global data sourcefunction HOC(WrappedComponent, selectData) { return class extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { data: selectData(GlobalDataSource, props), }; } componentDidMount() { // Listens to the changes added GlobalDataSource.addChangeListener(this.handleChange); } componentWillUnmount() { // Listens to the changes removed GlobalDataSource.removeChangeListener(this.handleChange); } handleChange() { this.setState({ data: selectData(GlobalDataSource, this.props), }); } render() { // Rendering the wrapped component with the latest data data return <WrappedComponent data={this.state.data} {...this.props} />; } };}We know HOC is a function that takes in a component and returns a component. In the code above, we have created a function called HOC which returns a component and performs functionality that can be shared across both the ArticlesList component and UsersList Component. The second parameter in the HOC function is the function that calls the method on the API endpoint. We have reduced the duplicated code of the componentDidUpdate and componentDidMount functions. Using the concept of Higher-Order Components, we can now render the ArticlesList and UsersList components in the following way: const ArticlesListWithHOC = HOC(ArticlesList, (GlobalDataSource) => GlobalDataSource.getArticles());const UsersListWithHOC = HOC(UsersList, (GlobalDataSource) => GlobalDataSource.getUsers());REMEMBER, we are not trying to change the functionality of each component, we are trying to share a single functionality across multiple components using HOC. |
|
| 17. |
How to pass data between react components? |
|
Answer» Parent Component to Child Component (using PROPS) With the help of props, we can send data from a parent to a child component. 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:
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. |
|
| 18. |
Name a few techniques to optimize React app performance. |
|
Answer» There are many ways through which one can optimize the performance of a React app, let’s have a look at some of them:
|
|
| 19. |
What are the different ways to style a React component? |
|
Answer» There are many different ways through which one can style a React component. Some of the ways are :
We can import this file inside the component and use it: import styles from './styles.module.css';class RandomComponent extends React.Component { render() { return ( <div> <h3 className="heading">This is a heading</h3> <p className={styles.paragraph} >This is a paragraph</p> </div> ); }} |
|
| 20. |
How to prevent re-renders in React? |
Answer»
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. |
|
| 21. |
Explain Strict Mode in React. |
|
Answer» 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:
|
|