Intermediate and Advanced Flashcards
Covers Intermediate and Advanced React Questions
What is the useTransition
hook?
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>}
</>
);
}
What is the purpose of the useContext
hook in React?
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.
What is the purpose of flushSync
in React?
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.
What is Concurrent React (Concurrent Mode)?
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.
What is Strict Mode in React and why is it useful?
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 to create a Custom hook in React?
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;
}
What are Synthetic Events in React?
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
}} />
What are Pure Components?
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>
);
};
What is the purpose of the useEffect
hook in React?
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.
What are use client
and use server
directives?
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.
Can you use hooks in Server Components?
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.
What is Hydration in React?
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 do you investigate a slow React app and identify performance bottlenecks?
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.
What is Reconciliation in React?
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.
What is the purpose of the useMemo
hook in React?
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.