React Coding Interview Questions & Answers with Coding Challenges

Shashipraba Perera
Stackademic
Published in
5 min readOct 22, 2023

--

  1. Explain the concept of Event Delegation in JavaScript. Why is it useful?

Event Delegation is where you attach a single event listener to a common ancestor element of multiple child elements instead of attaching listeners to each child element.

Helps to improve performance — when dealing with large number of elements, it reduces the number of event handlers.

2. Coding Challenge: Event Delegation in React?

Implement event delegation in a React component by attaching a click event listener to a parent element and handling the events for multiple child elements. For example, create a list of items, and when an item is clicked, log its text to the console.

Answer :

import React from 'react';

class EventDelegate extends React.Component{

handleClick = (event) => {
if(event.target.tagName === 'li'){
console.log(event.target.textContent);
}
};

render(){
return(
<ul onClick={this.handleClick}>
<li> Item 1 </li>
<li> Item 1 </li>
<li> Item 1 </li>
</ul>
);
}
}

export default EventDelegate

In the above example, we attach a single click event listener to the ul element and check the tagName property of the event target to identify which li element was clicked. This demonstrates the concept of event delegation.

3. What is the purpose of React Hooks, and how do they differ from class component lifecycle methods?

Functions that allow functional components to manage state and side effects. Hooks do not require you to write class-based components, so making code easier to understand and share logic between components.

4 . Coding Challenge: Refactoring to Functional Component with React Hooks.

Refactor a class-based React component into a functional component using React Hooks. For example, take a simple counter component and rewrite it using the useState Hook to manage state.

Answer :

import React, {useState} from 'react';

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

const increment= () => {
setCount(count + 1);
}

return(
<div>
<p> Count : {count} </p>
<button onClick={increment}> Increment </button>
</div>
);
}

export default Counter;

We refactored a class-based counter component to a functional component using the useState Hook to manage state.

5. What is a Higher-Order Component (HOC) in React, and why might you use one?

A pattern in React that allows you to reuse component logic by wrapping one or more components with a higher-order component. Often used to add features, behaviors, or data to components without modifying the original code. They promote reusability and separation of concerns.

memo

  • A high order component
  • Prevents re-rendering if the props are the same based on a shallow comparison.

useCallback

  • Returns a memoized reference of the callback function.
  • Reference changes if one of the dependencies has changed.

useMemo

  • Returns a memoized value.
  • Used to optimize expensive calculations.
  • Only recomputed when one of its dependencies changes.
  • return any memoized value unlike useCallback which returns a memoized function reference.

💡 Learn more about memoization here:

6. Coding Challenge: Creating a Higher-Order Component (HOC)

Create a Higher-Order Component that adds a loading spinner to a component until a specified condition is met. For instance, create an HOC that displays a loading spinner until data is fetched and displayed in a component.

Answer :

import React, {Component} from 'react';

const withLoading = (WrappedComponent) => {
return class WithLoading extends Component{
render(){
if(this.props.isLoading){
return <div> Loading... </div>
}
return <WrappedComponent {...this.props} />;
}
};
};

//usage
const WrappedComponentWithLoading = withLoading(SomeComponent);

// Later in your code, use WrappedComponentWithLoading instead of SomeComponent

We created a Higher-Order Component (HOC) called withLoading that displays a loading spinner until a specified condition (isLoading prop) is met.

7. Explain the concept of Redux in React. What problem does it solve, and how does it work?

Ref : https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/

Redux is a state management library for React. Helps manage the state of an application in a predictable and centralized manner. Use a single store to manage state of entire application & unidirectional data flow.

Actions -> Dispatched to change the state.

Reducers -> Specify how to change the state based on those actions

8. Coding Challenge: Redux for To-Do List

Set up a simple Redux store and create actions and reducers for a to-do list application. Implement adding, removing, and marking to-dos as completed.

Answer :

//actions.js
export const addToDo = (text) => ({
type:"Add ToDo",
text,
});
export const removeToDo = (id) => ({
type:"Remove ToDo",
id,
});
export const complete = (id) => ({
type:"Toggle complete",
id,
});


//reducers.js
const toDoreducer = (state, [], action) => {
switch (action.type){
case 'ÁDD_TODO':
return [
...state,
{id: state.length + 1, text: action.text, completed: false},
];
case 'REMOVE_TODO':
return state.filter((todo) => todo.id !== action.id);
case 'COMPLETE_TODO':
return state.map((todo_=>
todo.id === action.id ? {...todo, completed: !todo.completed } : todo
);
default:
return state;
}
};

export default todoReducer;

In this example, we set up actions and a reducer for a to-do list application using Redux. The todoReducer handles adding, removing, and toggling completion of to-do items.

9. What is the purpose of React Router, and how do you handle routing in a React application?

A library for handling routes within the applications. It allows you to,

  • Define routes in your application.
  • Map them to components.
  • Navigate between views without full page reloads.
  • Helps to create single-page application experience.

10. Coding Challenge : React Router for Multi-Page Application.

Build a simple multi-page React application using React Router. Create different routes for a home page, about page, and contact page. Implement navigation between these routes.

Answer:

import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

const Home = () => <div> Home page </div>;
const About = () => <div> About page </div>;
const Contact =() => <div> Contact page </div>;

function App(){
return(
<Router>
<nav>
<ul>
<li>
<Link to="/"> Home </Link>
</li>
<li>
<Link to="/about"> About </Link>
</li>
<li>
<Link to="/contact"> Contact</Link>
</li>
</ul>
</nav>

<Route path="/" exact component={Home}/>
<Route path="about" component={About}/>
<Route path="contact" component={Contact}/>
</Router>
);
}

export default App;

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--

Passionate about bridging the worlds of AI, Machine Learning and Development.