Intermediate and Advanced Flashcards

Covers Intermediate and Advanced React Questions

1
Q

What is the useTransition hook?

A

useTransition hook allows you to mark certain updates as transitions so they can be deprioritized, allowing other, more urgent updates to be processed first. This ensures that the UI remains responsive during updates that might take some time.

import { useTransition, useState } from ‘react’;
import { Posts } from ‘./Posts’;
import { Home } from ‘./Home’;
import { Contact } from ‘./Contact’;

export function App() {
const [isPending, startTransition] = useTransition();
const [page, setPage] = useState(‘home’);

function changePage(newPage: string) {
startTransition(() => {
setPage(newPage);
});
}

return (
<>
<button onClick={() => changePage(‘home’)}>Home</button>
<button onClick={() => changePage(‘posts’)}>Posts</button>
<button onClick={() => changePage(‘contact’)}>Contact</button>
<hr />
{isPending && <div>Loading…</div>}
{page === ‘home’ && <Home></Home>}
{page === ‘posts’ && <Posts></Posts>}
{page === ‘contact’ && <Contact></Contact>}
</>
);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the purpose of the useContext hook in React?

A

The useContext hook is used to access and consume context values in functional components.

useContext is particularly useful when you want to access context values in nested components without having to pass props through intermediate components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of flushSync in React?

A

The flushSync function in React is used to flush updates synchronously.

It schedules updates to be performed inside a high-priority task, ensuring that the updates are executed immediately and synchronously before returning control to the caller.

This is useful in situations where you need the DOM to be updated immediately, such as for measurements or to ensure synchronous rendering.

However, excessive use of flushSync can lead to degraded performance, so it should be used judiciously.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is Concurrent React (Concurrent Mode)?

A

Concurrent React, previously referred to as Concurrent Mode, is a set of new features in React that allows React to interrupt the rendering process to consider more urgent tasks, making it possible for React to be more responsive to user input and produce smoother user experiences.

It lets React keep the UI responsive while rendering large component trees by splitting the rendering work into smaller chunks and spreading it over multiple frames.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Strict Mode in React and why is it useful?

A

Strict Mode is a tool in React for highlighting potential problems in an application.

By wrapping a component tree with StrictMode, React will activate additional checks and warnings for its descendants.

This doesn’t affect the production build but provides insights during development.

In Strict Mode, React does a few extra things during development:
1. It renders components twice to catch bugs caused by impure rendering.
2. It runs side-effects (like data fetching) twice to find mistakes in them caused by missing effect cleanup.
3. It checks if deprecated APIs are used and logs a warning message to the console if so.

const root = createRoot(document.getElementById(‘root’));
root.render(

<StrictMode>
<App></App>
</StrictMode>

);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to create a Custom hook in React?

A

Custom hooks are a mechanism for code reuse in React and allow you to extract component logic into reusable functions.

Custom hooks can be used to share logic between components or to abstract away complex logic to make components more readable.

Custom hooks are named with the prefix use and can call other hooks if needed. They can also accept arguments and return values.

import { useState, useEffect } from ‘react’;

function useNetworkStatus() {
const [isOnline, setIsOnline] = useState(true);

useEffect(() => {
function handleOnline() {
setIsOnline(true);
}

function handleOffline() {
  setIsOnline(false);
}

window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);

return () => {
  window.removeEventListener('online', handleOnline);
  window.removeEventListener('offline', handleOffline);
};   }, []);

return isOnline;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are Synthetic Events in React?

A

React differs from HTML in that it uses a synthetic event system instead of directly binding to the browser’s native events.

This system brings consistency and performance benefits, and it allows React to be agnostic of environments like browser, server, or React Native.

Your event handlers will receive a React event object. It is also sometimes known as a “synthetic event”.

<button onClick={e => {
console.log(e); // React event object
}} />

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are Pure Components?

A

Pure components re-render only when the props passed to the component changes.

For example, if you have a pure child component inside a parent component state changes in the parent component will not re-render the child component unless the props passed to the child component change.

To create a pure component, you can use the memo function from React. It is a higher order component which takes a component as an argument and returns a new component. The new component renders only if the props change.

import React, { memo } from ‘react’;

const ChildComponent = ({ name }) => {
console.log(‘Rendering child component’);
return <div>{name}</div>;
};

const PureChildComponent = memo(ChildComponent);

const ParentComponent = () => {
const [count, setCount] = useState(0);
const [name, setName] = useState(‘John’);

return (
<div>
<button onClick={() => setCount(count + 1)}>Count - {count}</button>
<button onClick={() => setName(‘Jane’)}>Change name</button>
<PureChildComponent name={name} />
</div>
);
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the purpose of the useEffect hook in React?

A

The useEffect hook in React is used for performing side effects in functional components.

Side effects can include data fetching, DOM manipulation, and subscribing to external data sources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are use client and use server directives?

A

The use client directive marks source files whose components are intended to execute only on the client.

Conversely, use server marks server-side functions that can be invoked from client-side code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Can you use hooks in Server Components?

A

No, hooks are not supported in Server Components. Hooks are a client-side feature and are not supported in Server Components.

However, you can use hooks in client components and import them into Server Components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is Hydration in React?

A

Hydration is the process of using client-side JavaScript to add interactivity to the markup generated by the server.

When you use server-side rendering, the server returns a static HTML representation of the component tree.

Once this reaches the browser, t make it interactive, React “hydrates” the static content, turning it into a fully interactive application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you investigate a slow React app and identify performance bottlenecks?

A

There are many reasons why an app might be slow. It could be due to a slow network, a slow backend, or a slow client. It could also be due to a memory leak, unnecessary re-renders, or large bundle sizes.

Here are some tips to help you investigate and fix performance issues:

Use the React DevTools Profiler:
The React DevTools Profiler helps you visualize how components render and identify costly renderings. It can also help you identify unnecessary re-renders.

Check for Unnecessary Renders:
Ensure that components don’t render more often than needed. Be clear about the useEffect dependencies and avoid creating new objects or arrays every render, as these can trigger unnecessary child component renders. Tools like why-did-you-render can help spot unnecessary re-renders.

Analyze Bundle Size:
Use your production build to analyze your bundle size. Tools like webpack-bundle-analyzer or source-map-explorer can help you see if large libraries or unused code is slowing down the initial load.

Optimize Images & Assets:
Ensure images are appropriately sized and use modern formats. Also, consider using CDNs for assets that don’t change often.

Lazy Load Components:
Use lazy() and dynamic imports to split your bundle and load components only when they’re needed. This can help reduce the initial load time.

Check Network Requests:
Slow API calls or fetching large amounts of data can affect performance. Optimize your backend, paginate data, or cache results. You can also use tools like @tanstack/react-query or swr to help manage data fetching and caching.

Use Production Build for Testing:
Ensure you’re testing the performance on a production build, as development builds are often slower due to extra checks and logs.

Regularly profiling and monitoring your app can help you spot and fix performance issues before they become significant problems. You can use tools like Lighthouse or Calibre to monitor your app’s performance over time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is Reconciliation in React?

A

Reconciliation is the process through which React updates the DOM by comparing the newly returned elements with the previously rendered ones.

React updates the DOM when a component’s state changes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the purpose of the useMemo hook in React?

A

The useMemo hook is used to memoize the result of a computationally expensive operation in a functional component.

It helps optimize performance by caching the result of the operation and returning the cached result on subsequent renders if the dependencies have not changed.

This can prevent unnecessary calculations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How does React handle prop drilling, and what are the downsides of excessive prop drilling?

A

Prop drilling is the process of passing data from a parent component to deeply nested child components through props.

While React doesn’t prohibit this, it can lead to code that is hard to maintain and understand.

Excessive prop drilling can make it challenging to track data flow and can result in unnecessary re-renders.

To mitigate these issues, you can use Context API or state management libraries like Redux.

17
Q

How to lazy load components in React?

A

You can use React’s lazy() function in conjunction with dynamic import() to lazily load a component. This is often combined with Suspense to display fallback content while the component is being loaded.

// The component has to be exported as a default export
export default function RoadmapRender() {
return <h1>This is a lazily-loaded component!</h1>;
}

// App.jsx
import { lazy, Suspense } from ‘react’;

const LazyRoadmapRender = lazy(() => delay(import(‘./RoadmapRender’)));

export function App() {
const [showRoadmapRender, setShowRoadmapRender] = useState(false);
return (
<>
<button onClick={() => setShowRoadmapRender(true)}>
Show RoadmapRender
</button>
{showRoadmapRender && (
<Suspense fallback={<div>Loading…</div>}>
<LazyRoadmapRender></LazyRoadmapRender>
</Suspense>
)}
</>
);
}

// Helper function to simulate a 2 seconds delay
function delay(promise) {
return new Promise((resolve) => setTimeout(resolve, 2000)).then(
() => promise
);
}

The RoadmapRender component is lazily loaded and rendered inside the Suspense component. While the component is being loaded, the Suspense component will display the fallback content.

18
Q

What are Server Components in React?

A

Server Components allow developers to write components that render on the server instead of the client.

Unlike traditional components, Server Components do not have a client-side runtime, meaning they result in a smaller bundle size and faster loads.

They can seamlessly integrate with client components and can fetch data directly from the backend without the need for an API layer. This enables developers to build rich, interactive apps with less client-side code, improving performance and developer experience.

19
Q

What are Higher-Order Components (HOCs)?

A

A higher-order component (HOC) is a function that takes a component and returns a new component.

Basically, it’s a pattern that is derived from React’s compositional nature.

Higher-Order Components are not part of the React API. They are the pattern that emerges from React’s compositional nature.

20
Q

What are portals in React?

A

createPortal is a method on the ReactDOM object. It is used to render a React element into another DOM element outside of the parent component.

This is useful for cases like modals, popups, or tooltips where you want the component to break out of its container.

ReactDOM.createPortal(child, container);

The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element.

21
Q

How to render React components as static HTML string?

A

The renderToString function in React is part of the react-dom/server package and is used to render React components on the server-side to a static HTML string.

It is commonly used for server-side rendering (SSR) in React.

22
Q

What could be the reasons for un-necessary re-renders in React?

A

Unnecessary re-renders in components can occur due to several reasons, and it’s important to optimize your code to minimize them for better performance.

Here are some common reasons for unnecessary re-renders in functional components:

Using inline functions in JSX props: If you pass an inline function as a prop to child components, those components will get re-rendered every time the parent component re-renders. This is because a new function is created on every render. You can optimize this by using useCallback hook to memoize the function.

Using useState hook with objects: If you use useState hook with objects, you need to make sure that you are not mutating the object. If you mutate the object, React will not be able to detect the change and will not re-render the component. You can optimize this by using useReducer hook instead of useState hook.

Using useEffect hook without dependencies: If you use useEffect hook without dependencies, it will run on every render. You can optimize this by passing an empty array as the second argument to useEffect hook.

Parent Component Re-renders: If a parent component re-renders, all its child components will also re-render. You can optimize this by using React.memo to memoize the child component where possible.

Global State Changes: If you use global state management libraries like Redux, MobX, etc., and the global state changes, all the components that use that state will re-render. You can optimize this by using useSelector hook to select only the state that you need in a component.

Misusing Context: If you use Context API to pass data to child components, and the data changes, all the child components will re-render. You can optimize this by using useContext hook to select only the data that you need in a component.

23
Q

What is Context in React?

A

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context is primarily used when some data needs to be accessible by many components at different nesting levels.

24
Q

What is React Fiber?

A

React fiber is the reconciliation engine that replaced the core algorithm in React v16.

It is a rewrite of the core algorithm, responsible for scheduling what gets rendered on screen.

It is a set of algorithms for efficiently updating the UI.

25
Q

What are refs in React?

A

Refs are used to get reference to a DOM node or an instance of a component.

They help to access the DOM nodes or React elements created in the render method.

You can also use refs When you want a component to “remember” some information, but you don’t want that information to trigger new renders, you can use a ref.

26
Q

How React Virtual DOM works?

A

Virtual DOM works in this steps:

  1. Whenever any underlying data changes, new virtual DOM representation will be created.
  2. Then the difference between the previous DOM representation and the new one is calculated.
  3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
27
Q

What is ref forwarding in React?

A

By default, each component’s DOM nodes are private.

However, sometimes it’s useful to expose a DOM node to the parent—for example, to allow focusing it. To opt in, wrap your component definition into forwardRef()

You will receive a ref as the second argument after props. Pass it to the DOM node that you want to expose:

import { forwardRef } from ‘react’;

const MyInput = forwardRef(function MyInput(props, ref) {
const { label, …otherProps } = props;
return (
<label>
{label}
<input {…otherProps} ref={ref} />
</label>
);
});

This lets the parent Form component access their <input></input> DOM node exposed by MyInput:

function Form() {
const ref = useRef(null);

function handleClick() {
ref.current.focus();
}

return (
<form>
<MyInput label=”Enter your name:” ref={ref} />
<button type=”button” onClick={handleClick}>
Edit
</button>
</form>
);
}

28
Q

What is Suspense in React?

A

Suspense is a component in React that lets you specify the fallback content to display while waiting for a component to load.

It is used in conjunction with lazy() to lazily load components.

import { lazy, Suspense } from ‘react’;

const LazyRoadmapRender = lazy(() => import(‘./RoadmapRender’));

export function App() {
const [show, setShow] = useState(false);
return (
<>
<button onClick={() => setShow(true)}>Show</button>
{show && (
<Suspense fallback={<div>Loading…</div>}>
<LazyRoadmapRender></LazyRoadmapRender>
</Suspense>
)}
</>
);
}

Until the RoadmapRender component is loaded, the Suspense component will display the Loading… fallback content.

29
Q

Explain the concept of error boundaries in React.

A

Error boundaries are special React components that catch JavaScript errors during rendering, in lifecycle methods, and during the constructor of whole tree below them.

They are used to handle errors gracefully by displaying a fallback UI and preventing the entire application from crashing due to unhandled errors.

You can use react-error-boundary package to create error boundaries in your application. It provides a ErrorBoundary component that you can wrap around any component that might throw an error.

The ErrorBoundary component takes a FallbackComponent prop that is used to render a fallback UI when an error occurs.

import { ErrorBoundary } from ‘react-error-boundary’;
import { FetchData } from ‘./FetchData’;

function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}

export function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<FetchData></FetchData>
</ErrorBoundary>
);
}