FrontendDeveloper.in

React Interview Questions

Filter by topic:
  • By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

    component.forceUpdate(callback);
    

    It is recommended to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

  • When you want to access this.props in constructor() then you should pass props to super() method.

    Using super(props):

    class MyComponent extends React.Component {
    constructor(props) {
    super(props);
    console.log(this.props); // { name: 'John', ... }
    }
    }
    

    Using super():

    class MyComponent extends React.Component {
    constructor(props) {
    super();
    console.log(this.props); // undefined
    }
    }
    

    Outside constructor() both will display same value for this.props.

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

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

  • It is possible. Below are the possible options:

    render() {
    return false
    }
    
    render() {
    return true
    }
    
    render() {
    return null
    }
    

    React version >=16.0.0:

    render() {
    return []
    }
    
    render() {
    return ""
    }
    

    React version >=16.2.0:

    render() {
    return <React.Fragment></React.Fragment>
    }
    
    render() {
    return <></>
    }
    

    React version >=18.0.0:

    render() {
    return undefined
    }
    
    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 });
    
    1. Calling setState() with a function:
    this.setState((prevState) => ({
    user: {
    ...prevState.user,
    age: 42,
    },
    }));
    
  • There are approaches to include polyfills in create-react-app,

    1. Manual import from core-js:

    Create a file called (something like) polyfills.js and import it into root index.js file. Run npm install core-js or yarn add core-js and import your specific required features.

    import "core-js/fn/array/find";
    import "core-js/fn/array/includes";
    import "core-js/fn/number/is-nan";
    
    1. Using Polyfill service:

    Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html:

    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes"></script>
    

    In the above script we had to explicitly request the Array.prototype.includes feature as it is not included in the default feature set.

  • You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

    componentDidMount() {
    this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
    }
    
    componentWillUnmount() {
    clearInterval(this.interval)
    }
    
  • React's reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.

  • You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

    This can be done in two steps:

    1. Create ref in render method:
    <input ref={(input) => (this.inputElement = input)} />
    
    1. Apply click event in your event handler:
    this.inputElement.click();
    
  • 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>
    );
    }
    }
    }