What is React?
React is a front-end and open-source JavaScript library which is useful in developing user interfaces specifically for applications with a single page. It is helpful in building complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.
The important features of React are:
- It supports server-side rendering.
- It will make use of the virtual DOM rather than real DOM (Data Object Model) as RealDOM manipulations are expensive.
- It follows unidirectional data binding or data flow.
- It uses reusable or composable UI components for developing the view
What are the advantages of using React?
MVC is generally abbreviated as Model View Controller.
- Use of Virtual DOM to improve efficiency: React uses virtual DOM to render the view. As the name suggests, virtual DOM is a virtual representation of the real DOM. Each time the data changes in a react app, a new virtual DOM gets created. Creating a virtual DOM is much faster than rendering the UI inside the browser. Therefore, with the use of virtual DOM, the efficiency of the app improves.
- Gentle learning curve: React has a gentle learning curve when compared to frameworks like Angular. Anyone with little knowledge of javascript can start building web applications using React.
- SEO friendly: React allows developers to develop engaging user interfaces that can be easily navigated in various search engines. It also allows server-side rendering, which boosts the SEO of an app.
- Reusable components: React uses component-based architecture for developing applications. Components are independent and reusable bits of code. These components can be shared across various applications having similar functionality. The re-use of components increases the pace of development.
- Huge ecosystem of libraries to choose from: React provides you with the freedom to choose the tools, libraries, and architecture for developing an application based on your requirement
What are the limitations of React?
The few limitations of React are as given below:
- React is not a full-blown framework as it is only a library.
- The components of React are numerous and will take time to fully grasp the benefits of all.
- It might be difficult for beginner programmers to understand React.
- Coding might become complex as it will make use of inline templating and JSX.
What is UseState In Reactjs
In React.js, `useState` is a Hook that allows functional components to manage state. It's used to declare a state variable and returns a pair: the current state value and a function that updates it. This means you can store and update state in functional components without needing to use class-based components. It's a fundamental tool for managing dynamic data in React applications.or simply it is used to store variable
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.
What are keys in React?
A key is a special string attribute that needs to be included when using lists of elements
const ids = [1,2,3,4,5];
const listElements = ids.map((id)=>{
return(
<li key={id.toString()}>
{id}
</li>
)
})
What is JSX?
JSX stands for JavaScript XML. It allows us to write HTML inside JavaScript and place them in the DOM without using functions like appendChild( ) or createElement( ).
As stated in the official docs of React, JSX provides syntactic sugar for React.createElement( ) function.
Note- We can create react applications without using JSX as well.
What is the virtual DOM? How does react use the virtual DOM to render the UI?
As stated by the react team, virtual DOM is a concept where a virtual representation of the real DOM is kept inside the memory and is synced with the real DOM by a library such as ReactDOM.
In React.js, the Virtual DOM is a lightweight copy of the actual DOM (Document Object Model). It's a concept that allows React to efficiently update and render user interfaces. When changes are made to a component's state or props, React compares the Virtual DOM with the actual DOM and only updates the parts of the actual DOM that have changed. This helps improve performance and makes React applications faster and more efficient compared to traditional DOM manipulation.
What are the differences between controlled and uncontrolled components?
Controlled and uncontrolled components are just different approaches to handling input from elements in react
Controlled Components
In controlled components, React manages the input element's value, storing it in the component's state. When users input data, the onChange event triggers, allowing validation and state updates in real-time. This ensures synchronization between the UI and component state, facilitating controlled behavior and consistent updates.
function FormValidation(props) {
let [inputValue, setInputValue] = useState("");
let updateInput = e => {
setInputValue(e.target.value);
};
return (
<div>
<form>
<input type="text" value={inputValue} onChange={updateInput} />
</form>
</div>
);
}
As one can see in the code above, the value of the input element is determined by the state of the inputValue variable. Any changes made to the input element is handled by the updateInput function
Uncontrolled component: In an uncontrolled component, the value of the input element is handled by the DOM itself. Input elements inside uncontrolled components work just like normal HTML input form elements.
The state of the input element is handled by the DOM. Whenever the value of the input element is changed, event-based callbacks are not called. Basically, react does not perform any action when there are changes made to the input element.
Whenever use enters data inside the input field, the updated data is shown directly. To access the value of the input element, we can use ref.
function FormValidation(props) {
let inputValue = React.createRef();
let handleSubmit = e => {
alert(`Input value: ${inputValue.current.value}`);
e.preventDefault();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" ref={inputValue} />
<button type="submit">Submit</button>
</form>
</div>
);
}
As one can see in the code above, we are not using onChange function to govern the changes made to the input element. Instead, we are using ref to access the value of the input element
What is Props
In React, props (short for properties) are a way to pass data from parent components to child components. They allow components to be customizable and reusable by passing data as attributes. Props are read-only and help in creating dynamic and interactive components by providing data and configuration.
What is React Hooks?
React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.
Using Hook, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now using the useState hook, we can keep the state in a functional component
What are the rules that must be followed while using React Hooks?
There are 2 rules which must be followed while you code with Hooks:
- React Hooks must be called only at the top level. It is not allowed to call them inside the nested functions, loops, or conditions.
- It is allowed to call the Hooks only from the React Function Components
What is useeffects Hooks?
The useEffect hook in React is used to perform side effects in functional components. It lets you inform React that your component needs to do something after rendering or after a state change. This could include tasks like data fetching, setting up the document title, or manipulating the DOM directly. useEffect runs after the first render and after each update, ensuring that the DOM is updated before the effect runs. It takes two arguments: the callback function containing the side-effect logic, and an optional array of dependencies. The effect will only run if the dependencies change between renderings.
import { useEffect } from 'react';
function WelcomeGreetings({ name }) {
const msg = `Hi, ${name}!`; // Calculates output
useEffect(() => {
document.title = `Welcome to you ${name}`; // Side-effect!
}, [name]);
return <div>{msg}</div>; // Calculates output
}
The behavior of the useEffect hook depends on whether a dependency array is passed or not. Here's a breakdown:
If No Dependency Array is Passed
useEffect(() => {
console.log("Effect is running");
});
- What happens:
- The effect runs after every render, including the initial render and every subsequent re-render.
- This can lead to performance issues or infinite loops if the effect causes a state change that triggers a re-render.
- When to use:
- Rarely used, but might be applicable for scenarios where you need to run the effect on every render, e.g., logging render counts or tracking performance.
If an Empty Dependency Array [] is Passed
useEffect(() => {
console.log("Effect is running only once");
}, []);
- What happens:
- The effect runs only once, after the initial render.
- It won't run again on subsequent renders.
- When to use:
- For effects that need to run only once, such as:
- Fetching data on component mount.
- Setting up subscriptions or event listeners.
If Dependencies Are Provided in the Array
useEffect(() => {
console.log("Effect is running because count changed");
}, [count]);
- What happens:
- The effect runs only when the values in the dependency array change.
- React shallowly compares the dependencies (using
Object.is) to decide whether to re-run the effect. - When to use:
- For effects that depend on specific variables or props, such as:
- Updating a component when a prop or state changes.
- Syncing data or performing side effects tied to changes in dependencies.
When to Use the Dependency Array
- Empty Array (
[]):
- Use when the effect only needs to run once (e.g., on mount).
- Specific Dependencies (
[dep1, dep2]):
- Use when the effect should re-run only when certain variables change.
- No Array:
- Use sparingly, mainly when the effect needs to run after every render.
Common Pitfall
If you forget to add dependencies, React will show a warning:
React Hook useEffect has a missing dependency.
This ensures you don't unintentionally miss re-running the effect when its dependencies change.
What are Custom Hooks?
A Custom Hook is a function in Javascript whose name begins with ‘use’ and which calls other hooks. It is a part of React v16.8 hook update and permits you for reusing the stateful logic without any need for component hierarchy restructuring.
In almost all of the cases, custom hooks are considered to be sufficient for replacing render props and HoCs (Higher-Order components) and reducing the amount of nesting required. Custom Hooks will allow you for avoiding multiple layers of abstraction or wrapper hell that might come along with Render Props and HoCs.
The disadvantage of Custom Hooks is it cannot be used inside of the classes
import { useState } from "react";
const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => setCount((prev) => prev + 1);
const decrement = () => setCount((prev) => prev - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
};
export default useCounter;
import React from "react";
import useCounter from "./useCounter";
const CounterComponent = () => {
const { count, increment, decrement, reset } = useCounter(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
};
export default CounterComponent
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.
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
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
);
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:
- Use React.memo: Wrap your functional components with React.memo() to prevent re-rendering when their props and state remain unchanged.
- Optimize Render Method: Implement optimizations within your render method to avoid unnecessary re-renders. This might include memoizing expensive calculations or using shouldComponentUpdate in class components to prevent updates under certain conditions.
- Use PureComponent (for class components): Use PureComponent instead of Component for class components. PureComponent automatically performs a shallow comparison of props and state, preventing re-renders when there are no changes.
- Avoid Inline Function Definitions: Avoid defining functions within render methods, as doing so can create new function instances on each render, leading to unnecessary re-renders. Define functions outside the render method or use useCallback hook for memoizing function definitions.
- Use React.memo for child components: If you have child components that are not changing often, wrap them with React.memo to prevent unnecessary re-renders when their props don't change.
- Use Immutable Data Structures: Use immutable data structures (e.g., Immutable.js) to ensure that props and state updates create new references only when necessary. This helps React's reconciliation algorithm determine when components should re-render.
- Defer Updates with useEffect: If you have expensive operations that don't need to run synchronously during rendering, consider deferring them using useEffect with an empty dependency array. This ensures they only run once, after the initial render.
What are the different ways to style a React component?
There are many different ways through which one can style a React component. Some of the ways are :
- Inline Styling: We can directly style an element using inline style attributes. Make sure the value of style is a JavaScript object:
import React from 'react';
const MyComponent = () => {
return (
<div>
<h1 style={{ color: 'blue', backgroundColor: 'lightgray', padding: '10px', borderRadius: '5px' }}>Hello, Inline Styling!</h1>
<p style={{ fontSize: '16px', lineHeight: '1.5' }}>This is an example of inline styling in React.</p>
</div>
);
}
export default MyComponent;
- Using JavaScript object: We can create a separate JavaScript object and set the desired style properties. This object can be used as the value of the inline style attribute.
import React from 'react';
const MyComponent = () => {
const divStyle = {
color: 'blue',
backgroundColor: 'lightgray',
padding: '10px',
borderRadius: '5px'
};
return (
<div style={divStyle}>
<h1>Hello, Inline Styling!</h1>
<p>This is an example of inline styling in React.</p>
</div>
);
}
export default MyComponent;
- CSS Stylesheet: We can create a separate CSS file and write all the styles for the component inside that file. This file needs to be imported inside the component file.
import React from 'react';
import './MyComponent.css'; // Importing the CSS file
const MyComponent = () => {
return (
<div className="my-component">
<h1>Hello, CSS Styling!</h1>
<p>This is an example of styling React using a CSS stylesheet.</p>
</div>
);
}
export default MyComponent;
And in the corresponding CSS file (MyComponent.css), you can define the styles:
/* MyComponent.css */
.my-component {
color: blue;
background-color: lightgray;
padding: 10px;
border-radius: 5px;
}
.my-component h1 {
font-size: 24px;
}
.my-component p {
font-size: 16px;
line-height: 1.5;
}
- CSS Modules: We can create a separate CSS module and import this module inside our component. Create a file with “.module.css”‘ extension, styles.module.css:
/* styles.module.css */
.myHeading {
color: blue;
font-size: 24px;
}
.myParagraph {
color: green;
font-size: 18px;
}
And here's how you would use CSS Modules in a React component
import React from 'react';
import styles from './styles.module.css'; // Importing the CSS module
const MyComponent = () => {
return (
<div>
<h1 className={styles.myHeading}>Hello, Styling with CSS Modules!</h1>
<p className={styles.myParagraph}>This is an example of styling with CSS Modules in React.</p>
</div>
);
}
export default MyComponent;
How to pass data between react components?
1.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.
2.Child Component to Parent Component (using callbacks)
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.
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>
);
}
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>
);
}
What are Higher Order Components?
Simply put, Higher-Order Component(HOC) is a function that takes in a component and returns a new component.
a higher-order component is a function that takes a component and returns a new component with additional functionality
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.
import React, { useState, useEffect } from 'react'
// Higher-Order Component
const withDataFetching = (WrappedComponent, url) => {
return () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const data = await response.json();
setData(data);
setLoading(false);
} catch (error) {
setError(error.message);
setLoading(false);
}
};
fetchData();
// Cleanup function
return () => {
// Cleanup code (if needed)
};
}, [url]);
return (
<WrappedComponent
data={data}
loading={loading}
error={error}
/>
);
};
};
// Component that needs data fetching functionality
const MyComponent = ({ data, loading, error }) => {
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
// Enhance MyComponent with HOC
const MyComponentWithData = withDataFetching(MyComponent, "https://api.example.com/data");
// Usage
const App = () => (
<div>
<h1>Higher-Order Component Example</h1>
<MyComponentWithData />
</div>
);
export default App;
In this functional component example, withDataFetching is a higher-order component that takes the wrapped component (MyComponent) and a URL as parameters. It returns a functional component that uses hooks (useState and useEffect) to handle data fetching. The wrapped component receives the fetched data, loading state, and error as props
What are the different phases of the component lifecycle?
There are four different phases in the lifecycle of React component. They are:
- Initialization: During this phase, React component will prepare by setting up the default props and initial state for the upcoming tough journey.
- Mounting: Mounting refers to putting the elements into the browser DOM. Since React uses VirtualDOM, the entire browser DOM which has been currently rendered would not be refreshed. This phase includes the lifecycle methods
componentWillMountandcomponentDidMount. - Updating: In this phase, a component will be updated when there is a change in the state or props of a component. This phase will have lifecycle methods like
componentWillUpdate,shouldComponentUpdate,render, andcomponentDidUpdate. - Unmounting: In this last phase of the component lifecycle, the component will be removed from the DOM or will be unmounted from the browser DOM. This phase will have the lifecycle method named
componentWillUnmount.
What are the lifecycle methods of React?
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.
Explain about types of Hooks in React.
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:
- Basic Hooks:
useState(): This functional component is used to set and retrieve the state.useEffect(): It enables for performing the side effects in the functional components.useContext(): It is used for creating common data that is to be accessed by the components hierarchy without having to pass the props down to each level.- Additional Hooks:
useReducer(): It is used when there is a complex state logic that is having several sub-values or when the upcoming state is dependent on the previous state. It will also enable you to optimization of component performance that will trigger deeper updates as it is permitted to pass the dispatch down instead of callbacks.useMemo(): This will be used for recomputing the memoized value when there is a change in one of the dependencies. This optimization will help for avoiding expensive calculations on each render.useCallback(): This is useful while passing callbacks into the optimized child components and depends on the equality of reference for the prevention of unneeded renders.useImperativeHandle(): It will enable modifying the instance that will be passed with the ref object.useDebugValue(): It is used for displaying a label for custom hooks in React DevTools.useRef(): It will permit creating a reference to the DOM element directly within the functional component.useLayoutEffect(): It is used for the reading layout from the DOM and re-rendering synchronously.
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
Explain the MVC architecture?
The Model-View-Controller (MVC) framework is an architectural/design pattern that separates an application into three main logical components Model, View, and Controller. Each architectural component is built to handle specific development aspects of an application. It isolates the business, logic, and presentation layer from each other
Explain the building blocks of React?
The five main building blocks of React are:
- Components: These are reusable blocks of code that return HTML.
- JSX: It stands for JavaScript and XML and allows you to write HTML in React.
- Props and State: props are like function parameters and State is similar to variables.
- Context: This allows data to be passed through components as props in a hierarchy.
- Virtual DOM: It is a lightweight copy of the actual DOM which makes DOM manipulation easier.
How do browsers read JSX?
In general, browsers are not capable of reading JSX and only can read pure JavaScript. The web browsers read JSX with the help of a transpiler. Transpilers are used to convert JSX into JavaScript. The transpiler used is called Babel
How to create an event in React?
To create an event write the following code.
function Component() {
doSomething(e);
{
e.preventDefault();
// Some more response to the event
}
return <button onEvent={doSomething}></button>;
}
Explain the creation of a List in react?
Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying menus on a website, for example, the navbar menu. To create a list in React use the map method of array as follows.
import React from "react";
import ReactDOM from "react-dom";
const numbers = [1, 2, 3, 4, 5];
const updatedNums = numbers.map((number) => {
return <li>{number}</li>;
});
ReactDOM.render(<ul>{updatedNums}</ul>, document.getElementById("root"));
Explain the use of render method in React?
React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.
Explain one way data binding in React?
ReactJS uses one-way data binding which can be Component to View or View to Component. It is also known as one-way data flow, which means the data has one, and only one way to be transferred to other parts of the application. In essence, this means child components are not able to update the data that is coming from the parent component. It is easy to debug and less prone to errors.
What is conditional rendering in React?
Conditional rendering in React involves selectively rendering components based on specified conditions. By evaluating these conditions, developers can control which components are displayed, allowing for dynamic and responsive user interfaces in React applications.
{isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}
What is react router?
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
To install react router type the following command.
npm i react-router-dom
What is React Fragments?
In React, fragments are a way to group multiple elements without adding extra nodes to the DOM. This can be useful to avoid unnecessary wrapper elements when you need to return multiple children from a component. React provides a built-in Fragment component and a shorthand syntax for this purpose.
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} />
Handling Forms in React (Single & Multiple Inputs)
1. Single Input Handling
import { useState } from "react";
const SingleInputForm = () => {
const [value, setValue] = useState("");
return (
<form>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
};
export default SingleInputForm;
2. Multiple Inputs Handling
import { useState } from "react";
const MultipleInputForm = () => {
const [formData, setFormData] = useState({ name: "", email: "" });
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
return (
<form>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
};
export default MultipleInputForm;
Why Use name Attribute in Multiple Inputs?
- Identifies which field is being updated in the
handleChangefunction. - Enables dynamic updates using
[e.target.name]. - Prevents writing separate handlers for each input.
What is useMemo in React?
useMemois a React hook that returns a memoized value. It helps optimize performance by recalculating the result of a function only when its dependencies change.- Example:
const expensiveCalculation = (num) => {
console.log('Calculating...');
return num * 2;
};
const MyComponent = ({ number }) => {
const memoizedValue = useMemo(() => expensiveCalculation(number), [number]);
return <div>{memoizedValue}</div>;
};
What are fragments in React?
- Fragments allow you to group multiple elements without adding extra nodes to the DOM. It’s useful when you want to return multiple elements from a component without creating unnecessary wrapper elements.
- Example:
const MyComponent = () => {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
};
What are synthetic events in React?
- Synthetic events are React's cross-browser wrapper around the native DOM events. They provide consistency across different browsers and automatically handle event pooling for performance.
- Example:
const MyComponent = () => {
const handleClick = (event) => {
console.log(event.target); // Synthetic event object
};
return <button onClick={handleClick}>Click Me</button>;
};
What are the differences between package.json and package-lock.json?
package.jsoncontains the metadata about the project, including dependencies, scripts, and versions.package-lock.jsonensures that the exact same versions of dependencies are installed every time, making the build more predictable and stable.- Example:
package.json:
{
"dependencies": {
"react": "^17.0.0"
}
}
package-lock.json: Lists all exact versions of dependencies.
What are the differences between client-side and server-side rendering?
- Client-side Rendering (CSR): The browser loads a minimal HTML file and fetches JavaScript that then dynamically generates the page content.
- Example: React apps
- Server-side Rendering (SSR): The server generates the complete HTML and sends it to the browser, which then displays it.
- Example: Next.js with SSR
What is state in React?
- State is a built-in object in React components that stores data that can change over time. When state changes, the component re-renders.
- Example:
const MyComponent = () => {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
};
What is props drilling?
- Props drilling occurs when you pass data through many layers of components, even if the intermediate components don’t need the data.
- Example: Passing data from a parent to a deeply nested child through several intermediate components.
What are the disadvantages of props drilling and how can we avoid it?
- Disadvantages: Makes the code harder to maintain, especially when passing props to many nested components.
- Solution: Use Context API or state management libraries like Redux to avoid passing props through every layer.
- Example: Using Context API to avoid props drilling.
What are Pure components in React?
- A Pure Component is a component that only re-renders when its props or state change. It performs a shallow comparison of props and state for optimization.
- Example:
class MyPureComponent extends React.PureComponent {
render() {
return <div>{this.props.name}</div>;
}
}
What are Refs in React?
- Refs provide a way to access DOM nodes or React elements created in the render method. They are useful for managing focus, text selection, or media playback.
- Example:
const MyComponent = () => {
const inputRef = useRef();
const focusInput = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</>
);
};
What is meant by forward ref?
- Forward Ref allows you to pass a ref from a parent component to a child component.
- Example:
const MyInput = React.forwardRef((props, ref) => {
return <input ref={ref} />;
});
const Parent = () => {
const inputRef = useRef();
return <MyInput ref={inputRef} />;
};
What are Error Boundaries?
- Error Boundaries are components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of crashing the entire component tree.
- Example:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong</h1>;
}
return this.props.children;
}
}
What is useCallback?
useCallbackis a hook that returns a memoized version of a function, which only changes if one of its dependencies has changed.- Example:
const MyComponent = () => {
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <button onClick={handleClick}>Click</button>;
};
What are the differences between useMemo and useCallback?
useMemois used to memoize values or computed results, whileuseCallbackis used to memoize functions.useMemo: Optimizes expensive calculations.useCallback: Optimizes functions that are passed as props to child components.
What is Lazy loading in React?
- Lazy loading allows you to load components only when they are needed, rather than upfront. It helps in reducing the initial loading time.
- Example:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
const App = () => {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
);
};
What is Suspense in React?
- Suspense is a feature that allows you to declaratively specify a loading fallback while waiting for a component to load or fetch data.
- Example: Used with
React.lazy()to load components asynchronously.
What is useReducer Hook?
useReduceris a React hook used to manage more complex state logic, typically when the state depends on previous state or involves multiple sub-values.- Example:
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
};
const MyComponent = () => {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return <button onClick={() => dispatch({ type: 'increment' })}>Count: {state.count}</button>;
};
What are Portals in React?
- Portals provide a way to render a child component into a different part of the DOM that is outside the parent component’s hierarchy.
- Example:
const MyModal = () => {
return ReactDOM.createPortal(
<div className="modal">Modal Content</div>,
document.getElementById('modal-root')
);
};
What is the purpose of a callback function as an argument of setState()?
- The callback function in `
1. Differences between createElement vs cloneElement in React
React.createElement():- It is a React function used to create a new React element (virtual DOM element) from a given component or HTML tag.
- It is generally used behind the scenes in JSX code.
- Example:
const element = React.createElement('button', { className: 'btn' }, 'Click Me');
- This creates a React element of a
<button>with a class ofbtnand textClick Me. React.cloneElement():cloneElement()is used to clone an existing React element and modify its props before re-rendering.- It’s useful when you want to add or modify the props of an existing element, especially when dealing with children.
- Example:
const button = <button className="btn">Click Me</button>;
const clonedButton = React.cloneElement(button, { className: 'btn primary' });
- This creates a cloned element of the original button with a modified class (
btn primary). - Key Differences:
createElementis used to create new elements, whereascloneElementis used to modify an existing element.cloneElementallows you to modify props of an existing React element, whilecreateElementis for constructing a new one from scratch.
When to use useState and useReducer in React
useState:- Use
useStatewhen your component’s state is simple and can be updated based on the latest value. It is suitable for managing small states, like form inputs or toggling visibility. - Example:
const [count, setCount] = useState(0);
- When to use:
- Simple, isolated states (e.g., a boolean for toggling visibility or a number for counting).
- State does not depend on other state or involves a simple update.
useReducer:- Use
useReducerwhen your component’s state is more complex or when the state logic depends on multiple actions. It's beneficial when you have a more complicated state update logic or need to handle actions like in Redux-style architecture. - Example:
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, { count: 0 });
- When to use:
- When state transitions involve more than just setting a value (like incrementing, decrementing, toggling multiple state variables).
- When you need to handle multiple actions that affect the state.
- Complex or large state structures that need to be updated in a predictable manner.
What is flushSync in React?
flushSyncis a method in React that forces React to synchronously flush any pending updates to the DOM, ensuring that all updates are applied immediately before continuing with the rest of the code execution.- This is useful when you need to make sure that a specific DOM change happens right away, such as when performing an animation or updating the layout and you want React to commit the changes synchronously.
- Example:
import { flushSync } from 'react-dom';
const handleClick = () => {
flushSync(() => {
setCount(count + 1); // Ensures that this update is immediately reflected
});
};
- When to use
flushSync: - When you need to ensure that updates to state and DOM are immediately applied, rather than being batched asynchronously.
- It’s typically used in situations where you want precise control over the timing of updates, like when dealing with animations, measuring layout changes, or ensuring synchronous rendering behavior.
useMemo vs React.memo and their differences
useMemo:useMemois a React Hook that memoizes the result of a function and only recomputes it when its dependencies change.- It is used to optimize performance by memoizing expensive calculations so they are not re-executed unless necessary.
- Example:
const expensiveCalculation = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
React.memo:React.memois a higher-order component that wraps a component and prevents it from re-rendering unless its props change.- It’s used to optimize functional components by avoiding unnecessary re-renders.
- Example:
const MyComponent = React.memo((props) => {
// component logic
});
- Key Differences:
useMemois used for memoizing values (like computations) inside a component, whileReact.memois used to memoize components based on props comparison.useMemohelps with optimizing expensive calculations inside a component, whileReact.memoprevents unnecessary re-renders of components.
Why create a copy of the state when updating it in React?
In React, state is immutable, which means you shouldn’t modify the state directly. Instead, you should create a copy of the state and modify the copy. This helps React efficiently detect changes and re-render components.
- When updating arrays or objects, creating a copy ensures that React sees the change as a new reference, which triggers a re-render.
- Example:
const [items, setItems] = useState([1, 2, 3]); // Create a new array copy and update it const updatedItems = [...items, 4]; setItems(updatedItems); // This ensures a new reference and triggers a re-render.
Without creating a copy, React may not detect the change, and the component won’t re-render.
How can you prevent a component from re-rendering in React?
You can prevent a component from re-rendering by:
- Using
React.memofor functional components that only re-render if their props change. - Using
shouldComponentUpdatein class components to manually control whether a component should re-render. - Using
useMemoto memoize expensive calculations and prevent unnecessary re-computations. - Using
useCallbackto memoize functions passed as props to child components, preventing unnecessary re-renders.
Example:
const MyComponent = React.memo((props) => {
// Your component logic here
});
Basic Unit Test Cases for a Component
You can use libraries like Jest and React Testing Library for unit testing React components. Below is a basic example of testing a simple component:
- Component:
const Button = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);
- Test:
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
test('renders Button component and responds to click', () => {
const handleClick = jest.fn();
render(<Button label="Click Me" onClick={handleClick} />);
// Check if button renders correctly
expect(screen.getByText(/Click Me/i)).toBeInTheDocument();
// Simulate click event
fireEvent.click(screen.getByText(/Click Me/i));
// Check if handleClick function was called
expect(handleClick).toHaveBeenCalledTimes(1);
});
How would you check if an object is empty in JavaScript?
To check if an object is empty in JavaScript, you can use:
Object.keys():
const isEmpty = obj => Object.keys(obj).length === 0;
Object.entries()(to check both keys and values):
const isEmpty = obj => Object.entries(obj).length === 0;
If the length of keys or entries is 0, the object is empty.
What is the application of an Immediately Invoked Function Expression (IIFE)?
An IIFE is a function that runs immediately after it is defined. It is commonly used for:
- Avoiding polluting the global namespace by encapsulating variables inside the function.
- Creating a module pattern to encapsulate logic that should not be accessible globally.
Example:
(function() {
// Code here is executed immediately
let temp = 'I am inside IIFE';
console.log(temp);
})();
Explain Server-Side Rendering (SSR) and Experience
- Server-Side Rendering (SSR):
- In SSR, the initial HTML is generated on the server and sent to the browser. It provides a fully rendered page to the client, reducing the time for first contentful paint (FCP) and improving SEO.
- My experience with SSR:
- I've worked with frameworks like Next.js, which provides built-in SSR capabilities for React apps. In Next.js, you can pre-render pages at the server level to improve performance and SEO. Example:
export async function getServerSideProps() {
// Fetch data on the server
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
Implement a Cricket Score Functionality in a Table Format
Here’s an example of how to implement cricket score functionality with two columns: Ball Number and Number of Runs:
import React, { useState } from 'react';
const CricketScore = () => {
const [score, setScore] = useState([{ ball: 1, runs: 0 }]);
const handleUpdateScore = () => {
const newBall = score.length + 1;
const newRuns = Math.floor(Math.random() * 7); // Random runs between 0 and 6
setScore([...score, { ball: newBall, runs: newRuns }]);
};
return (
<div>
<table>
<thead>
<tr>
<th>Ball Number</th>
<th>Runs</th>
</tr>
</thead>
<tbody>
{score.map((entry, index) => (
<tr key={index}>
<td>{entry.ball}</td>
<td>{entry.runs}</td>
</tr>
))}
</tbody>
</table>
<button onClick={handleUpdateScore}>Update Score</button>
</div>
);
};
export default CricketScore;
How to Display Data from API in React
To display data from an API in React, you can use useEffect for fetching the data and useState for storing it:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const DisplayData = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get("https://api.example.com/data");
console.log(response.data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []);
return (
<div>
{data.length > 0 ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default DisplayData;
Explain useEffect
useEffect is a Hook in React that allows you to run side-effects (such as fetching data, subscribing to events, or manually changing the DOM) after a component renders. It takes a function that will be executed after the render.
- Basic usage:
useEffect(() => {
// Side-effect logic here
}, [dependencies]); // The effect runs whenever dependencies change
Explain Axios
Axios is a promise-based HTTP client for the browser and Node.js. It is used for making HTTP requests to fetch or send data from/to APIs.
- Example:
import axios from "axios";
const fetchData = async () => {
try {
const response = await axios.get("https://api.example.com/data");
console.log(response.data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
Lifting State Up in React
"Lifting state up" refers to moving the state of a child component to a common parent to enable sharing the state between sibling components. It makes it easier to synchronize state changes across multiple components.
Example:
const ParentComponent = () => {
const [score, setScore] = useState(0);
return (
<div>
<ChildComponent score={score} setScore={setScore} />
</div>
);
};
const ChildComponent = ({ score, setScore }) => (
<div>
<p>Current Score: {score} </p>
<button onClick={() => setScore(score + 1)}>Increase Score </button>
