Top React Interview Questions and Answers for 2023 – IQCode

Introduction to React

React is an open-source JavaScript library that is efficient, flexible, and used for building fast and scalable web applications. It was created by Jordan Walke, a software engineer at Facebook, and first deployed on Facebook's news feed in 2011 and later on Instagram in 2012. React is a popular choice among JavaScript developers due to its ease of use and simplicity.

React Hooks is a new feature that allows developers to use state and other features without requiring a class to be written. It is essentially a set of functions that connect React state with lifecycle features from function components. React Hooks was added in version 16.8.

React has become a popular choice for web development, with increasing demand for React certification. It is fast-growing, easy to learn, has clean abstraction, and reusable components. As React continues to evolve, it shows no signs of stopping.

React Interview Questions for Beginners

1. What is React?

Advantages of Using React

React has several advantages that make it a popular choice for building modern web applications. Here are some of the key benefits:

- **Efficiency:** React uses a virtual DOM, which allows it to update and render changes to the UI more efficiently than traditional DOM manipulation techniques. This makes React faster and more performant.

- **Reusability:** React's component-based architecture allows developers to create reusable UI elements that can be used throughout the application. This reduces development time and also makes it easier to maintain and update the code.

- **Scalability:** React is highly scalable and can be used to build applications of any size. It has a robust ecosystem of tools and libraries that make it easy to manage large and complex codebases.

- **Flexibility:** React is highly flexible and can be used with a variety of programming languages and frameworks. It also has support for server-side rendering, making it a great choice for building full-stack web applications.

- **Community:** React has a large and active community of developers who contribute to its development. This ensures that the framework is constantly evolving and improving, and also provides resources and support for developers who are using the framework.

Overall, React is a powerful and flexible framework that offers many benefits for building modern web applications.


Introduction: React is a popular JavaScript library used for building user interfaces. Although it has many benefits, there are also some limitations to using React.


  • React is just a view library, which means it only concerns itself with the rendering of the UI components and their state management. If you need to add additional functionalities, like routing or form validation, you will have to use external libraries or write custom code.
  • React can be difficult to learn for beginners. It may take some time to understand the philosophy of component-based architecture and the way React manages state and props.
  • React does not support two-way data binding. Developers need to write additional code to manage data between components and their state.
  • React can be overkill for small projects. If you only have a few components, using React may result in too much boilerplate code to set up the project.
  • React can be slower than other frameworks when rendering large amounts of data.

Conclusion: While React has its limitations, it is still a powerful tool for building user interfaces. Understanding its strengths and weaknesses can help developers make informed decisions about when and how to use React.

What is useState() in React?

The useState() is a hook in React that allows functional components to have state. It returns an array with two values - the current state and a function to update that state.

Here is an example of how to use the useState() hook:

    const [count, setCount] = useState(0);

In this example, the initial state of the count variable is set to 0. The setCount function can be called to update the count value.

Understanding Keys in React

Keys in React are unique identifiers that are assigned to the elements in an array. These keys are used by React to efficiently update or re-render a list of elements. When a key is assigned to an element, React uses it to keep track of the element's identity, making it easier and faster to perform updates or deletions.

In summary, keys in React help optimize rendering performance by providing a way for React to identify which elements have changed or been removed from a list.

Differences Between Functional and Class Components

In React, there are two types of components: functional and class components. The main differences between them are:

1. Syntax: Functional components are written as plain JavaScript functions, while class components are written using ES6 classes.

2. State Management: Functional components do not have state or lifecycle methods, while class components have both.

3. Performance: Functional components are generally lighter and faster than class components, but class components provide more features and control.

Overall, functional components are simpler and easier to write, while class components are more complex but offer more power and flexibility. The choice between them depends on the specific needs of your application.

Understanding the Virtual DOM in React

The Virtual DOM is a concept in React that involves the creation of a virtual representation of the DOM (Document Object Model). It is a lightweight copy of the actual DOM, created and manipulated in memory, rather than in a browser.

React uses the Virtual DOM as a tool to efficiently update and render the UI. Instead of making changes to the actual DOM every time a user updates or interacts with the application, React makes changes to the Virtual DOM. It then compares the modified Virtual DOM with the previous version of itself and identifies the differences between them (also known as "diffing").

Once the differences have been identified, React updates only the necessary parts of the actual DOM, which saves time and resources. This process is called "reconciliation."

In summary, the Virtual DOM is a useful tool for improving UI performance by minimizing the number of DOM manipulations required. React achieves this by using the Virtual DOM to efficiently update and reconcile changes to the UI. Code:


Differences between Controlled and Uncontrolled Components

In React, a controlled component is a component whose value is controlled by React. It means that the source of truth for the component's state lies in the parent component. The parent component passes down the value as props to the child component. Whenever the value changes, the parent component is notified, which then updates the state and passes down the new value to the child component.

On the other hand, an uncontrolled component is a component whose value is not controlled by React. It means that the source of truth for the component's state lies in the DOM. In an uncontrolled component, the initial value is set by a defaultValue prop, and any subsequent changes are handled by the DOM, not by React.

The key difference between these two components is that a controlled component gives more control to the parent component, while an uncontrolled component gives more control to the DOM. The choice between controlled and uncontrolled components depends on the specific use case and requirements of the component.


// Controlled component example class ControlledComponent extends React.Component { constructor(props) { super(props); this.state = {value: ''}; }

handleChange = (event) => { this.setState({value:}); }

handleSubmit = (event) => { alert('A value was submitted: ' + this.state.value); event.preventDefault(); }

render() { return (

); } }

// Uncontrolled component example function UncontrolledComponent(props) { let inputRef = React.createRef();

function handleSubmit(event) { alert('A value was submitted: ' + inputRef.current.value); event.preventDefault(); }

return (

); }

Props in React

In React, "props" is a shorthand for "properties", which are how components receive input data. These input data can to be passed from a parent component to a child component in order to configure it and render it in a particular way. Props are essentially objects that contain information to be passed down to a component. Once a component receives props, they become read-only values that cannot be modified.

Explanation of React State and Props

In React, state and props are used to manage and pass data between components.

State: State is used to manage the internal state of a component. It is an object that holds data that can be updated and accessed by the component. When the state updates, React automatically re-renders the component that uses the state. The state can only be updated using the setState() method, which is asynchronous. The initial state of the component is defined in the constructor.

Props: Props (short for properties) are used to pass data from a parent component to a child component. They are immutable, read-only values that can be accessed in the child component. The parent component passes the props to the child component as an attribute. When the props are updated, the child component is re-rendered with the new values.

In summary, state is used to manage the internal state of a component, while props are used to pass data from a parent component to a child component. Understanding the difference between state and props is crucial to building efficient and functional React components.

Types of Side Effects in React Components

In React components, side effects refer to actions that occur in addition to the main purpose of the component. These side effects can be of two types:

1. Render Side Effects: These effects occur during the rendering phase of a component and may have an impact on the component's output. Examples of render side effects include setting the title of a web page or adding a class to an element.

2. Lifecycle Side Effects: These effects occur during the lifecycle of a component and may involve interacting with APIs, updating the state, or working with timers. Examples of lifecycle effects include fetching data from a server or subscribing to a WebSocket.

It's important to handle side effects properly in React components to ensure that they don't cause unnecessary re-renders or have an adverse impact on the component's performance. The useEffect() hook is commonly used for managing side effects in functional components, while lifecycle methods like componentDidMount() and componentDidUpdate() are used in class components.

Understanding Prop Drilling in React

Prop drilling is a term used in React when a component needs to pass data to its nested child components through props, even though the parent component doesn't need the data itself. Essentially, props are being drilled down through multiple layers of components to reach the intended child component.

This can lead to code that is hard to maintain and modify because any changes to the data flow will require changing multiple layers of components.

One solution to this problem is to use React's context API, which allows data to be passed down through the component tree without the need for prop drilling. Another solution is to use state management libraries like Redux, which provide a global state object that can be accessed by any component, eliminating the need for prop drilling.

What are Error Boundaries?

Error boundaries are components in React that catch and handle any errors that occur during rendering, in the lifecycle methods of other components, or in the constructor of any child component. When an error is caught by an error boundary, it allows the rest of the application to continue functioning without crashing, and instead displays a fallback UI which helps the user to understand that an error has occurred. Error boundaries enable developers to create more robust and fault-tolerant applications.

// Example of an Error Boundary component:
class MyErrorBoundary extends React.Component {
    constructor(props) {
        this.state = { hasError: false };
    static getDerivedStateFromError() {
        return { hasError: true };
    componentDidCatch(error, info) {
        // log the error to an error reporting service
        console.error(error, info);
    render() {
        if (this.state.hasError) {
            // render fallback UI
            return <h1>Something went wrong.</h1>;
        // render children if no error occurred
        return this.props.children;

Introduction to React Hooks

React Hooks are functions that let developers add state and lifecycle methods to React function components. They were introduced in React version 16.8. Prior to this release, state and lifecycle methods could only be used in class components. With Hooks, functional components can now take advantage of features previously available only to class components. Hooks provide a simpler way of managing state and lifecycle of components, making code more concise and easier to read.

Explanation of React Hooks

React Hooks is a feature that was introduced in React version 16.8. It allows developers to use state and other React features in functional components instead of only in class components.

Hooks are essentially functions that let you “hook into” React state and lifecycle features from function components. The most commonly used hooks are:

1. useState - which allows you to use state in functional components. 2. useEffect - which allows you to use lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount) in functional components. 3. useContext - which allows you to use state provided by a React Context component.

Using hooks can help simplify and optimize your code, as it allows you to reuse stateful logic between components, and to separate concerns within a component.

In summary, React Hooks is a new feature in React that allows developers to use state and other React features in functional components, making it easier to reuse and separate logic within a component.

Rules for Using React Hooks

In React Hooks, there are certain rules that must be followed to ensure proper functionality:

1. Hooks can only be used at the top level of a functional component or a custom hook. 2. Hooks cannot be used in class components. 3. Hooks must always be called in the same order and cannot be conditionally called. 4. Hooks should not be called in loops, conditions, or nested functions. 5. Hooks should only be called from within a React function component or a custom hook.

By following these rules, React Hooks can be used effectively and efficiently in your projects.

What is the Use of useEffect React Hook?

The useEffect hook in React is used to perform side effects within a functional component. These side effects can include data fetching, setting up subscriptions, and manually changing the DOM.

The basic syntax of useEffect is:

useEffect(() => {
  // Do something here
}, []);

The first argument to useEffect is a function that will be executed after the component has rendered, and the second argument is an array of dependencies. The dependencies determine when the effect should be executed. If the dependency array is empty, the effect will only be executed once, after the initial render.

For example, if you want to fetch data from an API when the component loads, you can use the useEffect hook like this:

import { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('');
      const jsonData = await response.json();
  }, []);

  return (
    // Render the UI here

In this example, the fetchData function will be called after the component has mounted. Once the fetch request has completed, the data will be set using the setData function.

Overall, the useEffect hook is a powerful tool for managing side effects in your React functional components.

Why do React Hooks utilize refs?

Refs in React Hooks are utilized to interact with the DOM or particular components in a way that is more akin to traditional JavaScript. The useRef Hook is used to produce a reference object with a .current attribute that can be changed. This reference object persists between renders, unlike variables. This implies that you can utilize it to store a value and change it between re-renders, then immediately display the modified value. Therefore, it is utilized as a method of preserving mutable data between state updates. This is why React Hooks make use of refs.

What are Custom Hooks?

In React, custom hooks are reusable functions that allow developers to extract logic from components and use it in multiple places within the application. Custom hooks enable code reuse and make components more readable and manageable. They can be created by combining built-in React hooks like useState and useEffect, as well as other custom hooks. Custom hooks are named with a prefix of "use" and can be used in functional components just like any other React hook.

React Interview Question for Experienced: Explain Strict Mode in React

In React, Strict Mode is a tool that can be used to highlight potential problems in the application's code. When enabled, Strict Mode performs additional checks and warnings in the development environment.

To enable Strict Mode in React, you can wrap your application or a specific component with a `StrictMode` component:

import React from 'react';

ReactDOM.render( , document.getElementById('root') );

Notable benefits of Strict mode include:

- Identifying components with unsafe lifecycle methods - Warning about legacy string ref API usage - Detecting unexpected side effects in functions used in the `render` phase - Highlighting potential issues with the usage of `setState` and `context API`

Overall, using Strict Mode helps developers write better code and avoid potential issues in the application.

Preventing Re-renders in React

One way to prevent unnecessary re-renders in React is to use the shouldComponentUpdate lifecycle method.

This method is called before the component re-renders, and it provides a boolean value that determines whether or not the re-render should occur.

Another approach is to use React.memo(), which is a higher-order component that wraps a component and memoizes its props, preventing re-renders when the props have not changed.

Additionally, you can use React's useCallBack() hook to memoize functions and avoid their recreation on every re-render.

By implementing these techniques, you can optimize the performance of your React application by reducing the number of unnecessary re-renders.

Different Ways to Style a React Component

There are several ways to style a React component:

  1. CSS Stylesheets: You can use regular CSS stylesheets to style your components. Simply import the stylesheet in the component and apply the classes and styles to the elements.
  2. Inline CSS: You can also use inline styles, which are defined inside the component. Just set the style attribute on the HTML element and assign it an object containing the CSS properties and values.
  3. CSS Modules: This approach allows you to scope your CSS styles to specific components and avoid naming conflicts. You can import a CSS module in your component and apply the styles using class names.
  4. Styled Components: This is a library that lets you write CSS as JavaScript code. This way, you can keep the styles in the same file as the component and use props to pass dynamic values to the styles.

Choosing a styling approach depends on the project's requirements and personal preferences. It's recommended to use the approach that best fits the project's needs.

Techniques to Optimize React App Performance

React is a powerful tool for creating modern web applications, but sometimes these apps can experience performance issues if not optimized correctly. Here are a few techniques to improve the performance of React apps:

1. Use React.memo or PureComponent for components that don't need to re-render on every state change.
2. Use the shouldComponentUpdate lifecycle method to only update components when necessary.
3. Avoid using inline functions for event handlers, as this can cause unnecessary re-renders.
4. Use the React Developer Tools to identify and address any performance bottlenecks.
5. Implement lazy loading and code splitting to reduce the initial load time of the app.
6. Use the useMemo and useCallback hooks to optimize expensive computations and prevent unnecessary re-renders.
7. Implement server-side rendering to reduce the amount of work the client needs to do.
8. Use the React Profiler API to identify and optimize performance issues in specific components.
9. Minimize the size of the app's bundle by enabling tree shaking and code splitting.
10. Optimize images and other media to reduce the load times of the app.

By implementing these techniques, developers can significantly improve the performance of their React apps, resulting in a smoother user experience and happier users.

How to Pass Data between React Components?

In React, data can be passed between components through props. The parent component can pass data to its children components by setting attributes or props. The child component can access the passed data by using the props object.

Here is an example of passing data from a parent component to a child component:

import React from 'react';

class ParentComponent extends React.Component {
  render() {
    const data = "Hello World";
    return (
      <ChildComponent data={data} />

class ChildComponent extends React.Component {
  render() {
    return (

In this example, the ParentComponent passes the "Hello World" string to the ChildComponent through the "data" prop. The ChildComponent then displays this prop value by accessing it through "".

Note that props are read-only and cannot be modified within a component. If you need to modify data passed through props, it should be done in the parent component and passed again as new props.

Explanation of Higher Order Components

Higher Order Components, or HOCs, are a advanced technique in React for reusing component logic. A HOC is, in fact, a function that takes a component and then returns a new component that enhances the function of the original component. HOCs help to reduce code duplication, and they improve the organization and maintenance of React applications. They also serve as a way to share functionality between different components. By using Higher Order Components, components can be more modular, scalable and flexible.

Phases of Component Lifecycle

In the context of React, there are three main phases in the component lifecycle:

1. Mounting: This is the phase where the component is created and inserted into the DOM. The methods that are called during this phase include constructor(), static getDerivedStateFromProps(), render(), and componentDidMount().

2. Updating: This is the phase where the component is updated when there are changes in the state or props. The methods that are called during this phase include static getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate(), and componentDidUpdate().

3. Unmounting: This is the phase where the component is removed from the DOM. The method that is called during this phase is componentWillUnmount().

It is important to understand the different phases of the component lifecycle in order to properly manage component state and properly handle component updates. Proper management can lead to optimized performance and improved user experience.

React Component Lifecycle Methods

In React, the lifecycle methods are a set of methods that are called at various stages of a component's lifecycle. These methods can be used to perform certain tasks when a component is created, updated, or destroyed.

The lifecycle methods can be categorized into three phases: mounting, updating, and unmounting.

1. Mounting - These methods are called when an instance of a component is created and inserted into the DOM.

- constructor() - static getDerivedStateFromProps() - render() - componentDidMount()

2. Updating - These methods are called when a component is updated, either by changes to props or state.

- static getDerivedStateFromProps() - shouldComponentUpdate() - render() - getSnapshotBeforeUpdate() - componentDidUpdate()

3. Unmounting - This method is called when a component is being removed from the DOM.

- componentWillUnmount()

By using these lifecycle methods correctly, we can control the behavior of our components and create more efficient and effective React applications.

Can React Hooks Be Used with Static Typing?

Yes, React Hooks work with static typing. You can use TypeScript or Flow to add static typing to your React Hooks code. This helps catch any potential errors before runtime and can make it easier to maintain and debug your code.

When using React Hooks with static typing, you'll typically define the types of your hooks using interfaces. For example, if you have a useState hook that returns a tuple of state and setState, you can define an interface for it like this:

interface StateTuple { state: string; setState: (state: string) => void; }

const [state, setState] = useState("initial state"); const stateTuple: StateTuple = {state, setState};

By defining the types of your hooks and variables, you can ensure that your code is more robust and avoid issues that can arise due to type mismatches or undefined variables.

Types of Hooks in React

React hooks are functions that allow us to use React state and lifecycle methods in functional components. There are several types of hooks in React, including:

1. useState: This hook is used for setting and updating state in a functional component. 2. useEffect: This hook is used for handling component lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount. 3. useContext: This hook is used for consuming context in a functional component. 4. useReducer: This hook is used for more complex state management, similar to Redux. 5. useCallback: This hook is used to memoize functions so that they are not recreated on every render. 6. useMemo: This hook is used to memoize values so that they are not recalculated on every render. 7. useRef: This hook is used for creating a mutable reference that persists between renders. 8. useImperativeHandle: This hook is used for exposing a child component's methods to its parent component.

Using hooks can make functional components more powerful and easier to manage. It is important to use the appropriate hooks for each situation to ensure efficient and effective code.

Difference Between React Hooks and Classes

React Hooks and Classes are two different ways of building components in React. Hooks were introduced in React 16.8 as a simpler and more efficient way of managing state and lifecycle methods in functional components. Classes, on the other hand, have been part of React since its inception and were the traditional way of building components.

Hooks are functions that allow you to use state and other React features in functional components without needing to write a class. This makes them easier to read, write, and maintain. With Hooks, you can use state, context, refs, and other React features in functional components without the need for a class.

Classes, on the other hand, are more complex and require you to extend the React.Component class. They have a more verbose syntax and require you to manually bind your event handlers. Classes are still useful, however, for components that need access to lifecycle methods or that have complex state management.

In summary, Hooks are a simpler and more efficient way of managing state and lifecycle methods in functional components, while classes are still useful for components that require access to lifecycle methods or have complex state management. Ultimately, the choice between Hooks and Classes comes down to personal preference and the specific needs of your application.

Performance Comparison between React Hooks and Classes

In terms of performance, using hooks in React is generally faster than using classes. This is because hooks allow for functional components, which can avoid the overhead of creating and managing class instances. Hooks also enable better code reuse and more efficient updates to state and props. However, the performance difference may not be noticeable in small applications, and ultimately the choice between hooks and classes should be based on the specific needs and requirements of the project.

Coverage of functionalities by hooks versus classes

Hooks provide most of the functionalities that are provided by classes, but not all. However, hooks offer a more streamlined and efficient way of managing state and handling side effects in React components. It is recommended to use hooks whenever possible, but in some cases, classes may still be necessary.

Understanding React Router

React Router is a powerful routing library built on top of the React library. It allows developers to implement client-side navigation in a React application by providing a set of components that can be used to define different routes of the application. React Router keeps the UI of the application in sync with the URL, making it easy to create complex applications with multiple pages.

Can React Hooks Replace Redux?

React Hooks offer a simpler way to manage state within a React component, making it possible to use functional components with state. While it is possible to manage application state with React Hooks alone, Redux is still a valuable tool, especially for larger applications with complex state management needs.

// Example React Hook for managing state
import React, { useState } from 'react';
function ExampleComponent() {
  const [count, setCount] = useState(0);
  function handleClick() {
    setCount(count + 1);
  return (
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment Count</button>
// Example Redux code for managing state
import { createStore } from 'redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + 1 };
      return state;
const store = createStore(reducer);
function ReduxExample() {
  const count = store.getState().count;
  function handleClick() {
    store.dispatch({ type: 'increment' });
  return (
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment Count</button>

Both React Hooks and Redux have their own strengths and weaknesses, so it ultimately depends on the specific needs and goals of your application. However, for simpler applications, React Hooks alone may be sufficient for managing state.

Conditional Rendering in React

In React, conditional rendering refers to rendering different outcomes based on certain conditions. This is achieved through the use of JavaScript conditional statements, for example, if/else statements, ternary operators, and switch statements.

Here's an example of conditional rendering in React using the ternary operator:

  {isLoggedIn ? <p>Welcome user!</p> : <p>Please log in.</p>}

In the code above, if the isLoggedIn variable is true, the user will be greeted with a "Welcome user!" message. Otherwise, they will be prompted to log in with a "Please log in." message.

Conditional rendering is a powerful feature in React that allows for dynamic and customized user interfaces based on certain conditions.

Creating a Simple React Hooks Example Program

To create a simple React Hooks example program, follow these steps:

1. Install the latest version of Node.js on your system. This will include the npm package manager, which you will use to install the necessary packages and dependencies. 2. Create a new React project by running the command `npx create-react-app my-app` in your terminal. This will create a new React application in a folder named 'my-app'. 3. Change to the 'my-app' directory (`cd my-app`) and open it in your code editor of choice. 4. Create a new file 'Counter.js' inside the 'src' folder. In this file, define a functional component named 'Counter'. 5. Inside the 'Counter' component, declare a state variable called 'count' using the 'useState' hook. The initial value of this variable should be set to 0. 6. Create a button element in the 'Counter' component's return statement with an `onClick` function that calls the 'setCount' function to increment the 'count' state variable by one on each click. 7. Save the 'Counter.js' file. 8. In the 'App.js' file, import the 'Counter' component by adding the line `import Counter from './Counter'`. 9. Use the 'Counter' component by adding the `` tag in the 'App.js' file's return statement. 10. Save the 'App.js' file. 11. In the terminal, navigate to the 'my-app' directory and run the command `npm start`. 12. Open your browser and go to `http://localhost:3000`. You will see the 'Counter' component rendered on the screen, with a button that increments the count value on each click.



import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me

export default Counter;


import React from 'react';
import Counter from './Counter';

function App() {
  return (
    <div className="App">
      <Counter />

export default App;

Creating a Switching Component to Display Different Pages

In order to create a switching component to display different pages, we can utilize conditional rendering and state management in React.

First, we can create a state variable to keep track of which page is currently being displayed:

const [currentPage, setCurrentPage] = useState('home');

Next, we can create a function to update the state variable when a different page is selected:

const handlePageChange = (page) => {

Then, we can use conditional rendering to display the appropriate page based on the value of the `currentPage` variable:

return (
        {currentPage === 'home' && <HomePage />}
        {currentPage === 'about' && <AboutPage />}
        {currentPage === 'contact' && <ContactPage />}

Finally, we can create a component to render the page navigation and call the `handlePageChange` function when a different page is selected:

const PageNavigation = () => {
    return (
                <li onClick={() => handlePageChange('home')}>Home</li>
                <li onClick={() => handlePageChange('about')}>About</li>
                <li onClick={() => handlePageChange('contact')}>Contact</li>

By using state management and conditional rendering, we can easily create a switching component to display different pages in our React application.

How to Re-render the view when the browser is resized?

In JavaScript, we can detect that the browser window has been resized using the `window.onresize` event. To re-render the view, we can call a function that updates the view and bind it to this event.

Here's an example:

// Get the element that needs to be updated
const element = document.querySelector('.my-element');

// Define a function to update the element
function updateElement() {
  // Code to update element goes here

// Call updateElement function on window resize event
window.onresize = function() {

In the above code, we first get the element that needs to be updated using `document.querySelector`. Next, we create a function named `updateElement` that contains the code to update the element.

Finally, we bind the `updateElement` function to the `window.onresize` event using an anonymous function. This means that whenever the window is resized, the `updateElement` function will be called to update the element.

Passing Data between Sibling Components with React Router

In React, passing data between sibling components can be challenging. However, React Router provides an elegant solution to this problem.

To pass data between sibling components, we can make use of the "render" method provided by the Route component. We can define this method to render the component and pass down any data as props.


import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Component1 from './Component1';
import Component2 from './Component2';

class App extends React.Component {
  state = {
    data: 'some data'

  render() {
    return (
          <Route path="/component1" render={() => (
            <Component1 data={} />
          )} />
          <Route path="/component2" component={Component2} />

export default App;

In this example, we define two components, Component1 and Component2. We use the Route component to define the routes for these components. We pass data down to Component1 using the render method and props.

In Component1, we can access this data by using the props object:

import React from 'react';

class Component1 extends React.Component {
  render() {
    return (

export default Component1;

By using this method, we can easily pass data between sibling components using React Router.

How to Perform Automatic Redirect After Login?

To perform an automatic redirect after login, you can use the header() function in PHP. First, you need to check if the user has entered the correct login details. If the credentials are correct, set a session variable and use the header() function to redirect the user to the desired page. Here's an example:

  // Check if the user has entered correct login details<br>
  if($username == 'correct_username' && $password == 'correct_password') {<br>
    // Set session variable<br>
    $_SESSION['logged_in'] = true;<br>
    // Redirect to desired page<br>
    header('Location: dashboard.php');<br>
  } else {<br>
    // Display error message<br>
    echo "Incorrect username or password";<br>

In the example above, if the user enters the correct username and password, the session variable 'logged_in' is set to true, and the user is redirected to the dashboard.php page using the header() function. If the credentials are incorrect, an error message is displayed.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.