WebNovels

Chapter 2 - React.js

What is React?

React is an open-source front-end JavaScript library used for building user interfaces, specifically for single-page applications. It is component-based and declarative.

What is the history behind React's evolution?

It was created by Jordan Walke at Facebook, influenced by XHP. First deployed on Facebook's newsfeed in 2011 and open-sourced at JSConf US in May 2013.

What are the major features of React?

Key features include the Virtual DOM, JSX, Unidirectional Data Flow, Server-Side Rendering, and a component-based architecture.

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like structures directly within JavaScript code.

What is the difference between an Element and a Component?

An Element is a plain object describing what you want to see on the screen. A Component is a function or class that accepts input (props) and returns elements.

How do you create components in React?

You can create components as JavaScript functions (Function Components) or by extending React.Component (Class Components).

When should you use a Class Component over a Function Component?

In modern React, Function Components with Hooks are preferred. Class components are generally only needed for Error Boundaries or legacy codebases.

What are Pure Components?

Components that only re-render if their props or state have changed (shallow comparison). React.PureComponent handles shouldComponentUpdate automatically.

What is state in React?

State is a built-in object that allows components to create and manage their own data. Unlike props, state is mutable and managed within the component.

What are props in React?

Props (short for properties) are read-only inputs passed from a parent component to a child component to configure it.

What is the difference between state and props?

Props are immutable and passed from parent to child. State is mutable and managed internally by the component itself.

What is the difference between HTML and React event handling?

React events use camelCase (e.g., onClick vs onclick), pass a function reference rather than a string, and cannot return false to prevent default behavior.

What are synthetic events in React?

React wraps native browser events in SyntheticEvent objects to ensure consistent behavior across different browsers.

What are inline conditional expressions?

These are expressions used inside JSX to render content conditionally, often using the logical AND operator (&&) or ternary operators.

What is the "key" prop and what is its benefit when used in arrays of elements?

A "key" is a unique string attribute for list items. It helps React identify which items have changed, been added, or removed, optimizing re-renders.

What is the Virtual DOM?

A lightweight JavaScript representation of the real DOM. React modifies this virtual copy and syncs changes to the real DOM (reconciliation).

How does the Virtual DOM work?

When state changes, React updates the Virtual DOM, compares it with the previous version (diffing), and efficiently updates only the changed parts of the real DOM.

What is the difference between Shadow DOM and Virtual DOM?

Shadow DOM is a browser technology for scoping CSS and variables (Web Components). Virtual DOM is a concept used by libraries like React on top of the browser APIs.

What is React Fiber?

Fiber is the reconciliation engine introduced in React 16. It allows splitting rendering work into chunks and prioritizing tasks (concurrency).

What is the main goal of React Fiber?

Its main goal is to enable incremental rendering and better performance for animations and gestures by pausing and resuming work.

What are controlled components?

Form components where the form data is handled by the React component's state rather than the internal DOM state.

What are uncontrolled components?

Form components where the form data is handled by the DOM itself. Values are accessed using Refs.

What is the difference between createElement and cloneElement?

createElement creates a new element from a type and props. cloneElement copies an existing element and merges new props into it.

What is Lifting State Up in React?

The process of moving state to a common ancestor component so that it can be shared between sibling components via props.

What are Higher-Order Components?

A pattern where a function takes a component and returns a new component, used for reusing component logic.

What is the children prop?

A special prop that allows you to pass components, text, or HTML elements as data to other components by nesting them inside the opening and closing tags.

How do you write comments in React?

Inside JSX, comments are written wrapped in curly braces: {/* This is a comment */}.

What is reconciliation?

The process through which React updates the DOM by diffing the Virtual DOM tree with the previous one to determine the most efficient updates.

Does the lazy function support named exports?

No, React.lazy currently supports default exports. You must re-export named exports as default in an intermediate module to use them.

Why does React use className instead of the class attribute?

class is a reserved keyword in JavaScript. Since JSX is transformed into JavaScript, className is used to define CSS classes.

What are Fragments?

Fragments ( or <>...) let you group a list of children without adding extra nodes (like extra divs) to the DOM.

Why are Fragments better than container divs?

They avoid DOM clutter, prevent invalid HTML (e.g., inside tables/lists), and reduce memory usage by not creating unnecessary nodes.

What are portals in React?

Portals provide a way to render children into a DOM node that exists outside the DOM hierarchy of the parent component (e.g., for modals).

What are stateless components?

Components that do not hold or manage state. They simply receive props and render UI.

What are stateful components?

Components that hold and manage local state, causing the component to re-render when that state changes.

How do you apply validation to props in React?

You can use the prop-types library to define the type and requirement (e.g., isRequired) of each prop passed to a component.

What are the advantages of React?

Fast rendering via Virtual DOM, reusable components, strong community, unidirectional data flow, and rich ecosystem (React Native, Next.js).

What are the limitations of React?

It is just a library (not a full framework), requires learning JSX, and the fast-paced ecosystem can lead to "churn" in best practices.

What are the recommended ways for static type checking?

TypeScript is the industry standard. Flow was used historically but has declined in popularity compared to TypeScript.

What is the use of the react-dom package?

It provides DOM-specific methods that can be used at the top level of your app to connect React components to the web page (e.g., render, hydrate).

What is ReactDOMServer?

A package that enables you to render components to static markup (HTML strings), primarily used for Server-Side Rendering (SSR).

How do you use innerHTML in React?

Use the dangerouslySetInnerHTML prop with an object containing a __html key. This acts as a warning about XSS risks.

How do you apply styles in React?

You can use CSS classes (className), inline styles (objects), CSS Modules, or CSS-in-JS libraries like Styled Components.

How are events different in React?

React events are synthetic (cross-browser wrappers), use camelCase naming, and are pooled (in older versions) for performance.

What is the impact of using indexes as keys?

It can cause performance issues and bugs with component state if the list order changes (sorting, filtering) or items are added/removed.

How do you conditionally render components?

Use if-else statements outside JSX, or ternary operators (cond ? A : B) and logical AND (cond && A) inside JSX.

Why we need to be careful when spreading props on DOM elements?

You might accidentally pass invalid HTML attributes to the DOM node or overwrite existing props with unwanted values.

How do you memoize a component?

Use React.memo() for function components to prevent re-renders if props haven't changed.

How do you implement Server-Side Rendering (SSR)?

Use ReactDOMServer.renderToString() on the server to generate HTML, send it to the client, and use hydrateRoot to attach event listeners.

How do you enable production mode in React?

Set the NODE_ENV environment variable to production during the build process (e.g., using Webpack or Vite).

Do Hooks replace render props and higher-order components?

Yes, in most cases Hooks provide a cleaner, less nested way to share logic, though the other patterns are still valid.

What is a switching component?

A component that renders one of many components based on a prop (e.g., a generic rendering specific SVGs).

What are React Mixins?

An obsolete way to share code between class components. They are deprecated and replaced by HOCs and Hooks.

What are the pointer events supported in React?

React supports standard pointer events like onPointerDown, onPointerMove, onPointerUp, onPointerEnter, etc.

Why should component names start with a capital letter?

React interprets lowercase tags as native HTML elements (like div) and capitalized tags as custom React components.

Are custom DOM attributes supported in React v16?

Yes, React 16+ allows custom attributes (including those without data- prefix), passing them through to the DOM.

How do you loop inside JSX?

You cannot use for loops directly. Use Array.prototype.map to iterate over data and return elements.

How do you access props within attribute quotes?

You don't use quotes. Use curly braces: .

What is a React PropType array with shape?

It defines an array of objects where the objects must match a specific schema: PropTypes.arrayOf(PropTypes.shape({...})).

How do you conditionally apply class attributes?

Use template literals or a utility library like clsx or classnames: className={`btn ${isActive ? 'active' : ''}`}.

What is the difference between React and ReactDOM?

React contains the core component logic. ReactDOM is the glue that renders that logic into the web browser DOM.

Why is ReactDOM separated from React?

To decouple the logic from the rendering target. React can be used with react-native, react-three-fiber, etc., not just the web.

How do you use the React label element?

Use htmlFor instead of the standard for attribute: .

How do you combine multiple inline style objects?

Use the spread operator or Object.assign: style={{ ...styleA, ...styleB }}.

How do you re-render the view when the browser is resized?

Add a resize event listener in useEffect (or componentDidMount) that updates a state variable holding the dimensions.

How do you pretty-print JSON with React?

Use the

 tag: 
{JSON.stringify(data, null, 2)}
.

Why can't you update props in React?

Props are read-only (immutable) to ensure unidirectional data flow, making the application predictable and easier to debug.

How do you focus an input element on page load?

Use a ref and call ref.current.focus() inside a useEffect hook (or componentDidMount).

How can you find the version of React at runtime in the browser?

You can check React.version in the console or your code.

How do you add Google Analytics for React Router?

Listen to location changes via useLocation or history API and trigger a page view event to GA on route change.

How do you apply vendor prefixes to inline styles in React?

React does not automatically auto-prefix inline styles. You must add them manually or use a library to handle prefixing.

How do you import and export components using React and ES6?

Use export default Component or export const Component; import via import Component from './path'.

What are the exceptions to React component naming?

Component names must start with a capital letter. Hooks must start with "use".

Is it possible to use async/await in plain React?

Yes, inside lifecycle methods or useEffect, but the useEffect callback itself cannot be async (call an async function inside it).

What are common folder structures for React?

Grouping by file type (components, services), or grouping by feature/domain (e.g., UserProfile folder containing component, styles, and tests).

What are popular packages for animation?

Framer Motion, React Spring, and React Transition Group.

What are the benefits of style modules?

They automatically scope CSS to the component (generating unique class names), preventing style conflicts globally.

What are popular React-specific linters?

ESLint with eslint-plugin-react and eslint-plugin-react-hooks.

What is React Router?

A standard library for routing in React. It enables navigation among views/components and keeps the UI in sync with the URL.

How is React Router different from the history library?

React Router is a wrapper around the history library that provides React components and hooks for routing.

What are the components of React Router v6?

Key components include BrowserRouter, Routes, Route, Link, and NavLink.

What is the purpose of the push and replace methods of history?

push adds a new entry to the history stack (back button works). replace replaces the current entry (back button skips the replaced page).

How do you programmatically navigate using React Router v4?

Access history via props (HOC) or context and call history.push('/path').

How do you get query parameters in React Router v4?

Use this.props.location.search and parse it using URLSearchParams or a library like query-string.

Why do you get a "Router may have only one child element" warning?

In older versions, could only wrap a single root child. You had to wrap children in a

.

How do you pass params to the history.push method in React Router v4?

history.push({ pathname: '/path', state: { detail: 'data' } }).

How do you implement a default or NotFound page?

Use a } /> as the last route definition.

How do you get history in React Router v4?

Use the withRouter HOC to inject history into component props.

How do you perform an automatic redirect after login?

Use the component (v6) or history.push inside the login success callback.

What is React Intl?

A library that provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.

What are the main features of React Intl?

Formatting for numbers/dates, pluralization, and message translation support using standard ICU syntax.

What are the two ways of formatting in React Intl?

Using React components (e.g., ) or the imperative API (e.g., intl.formatDate()).

How do you use FormattedMessage as a placeholder with React Intl?

Use the defaultMessage prop or the description prop for context, usually within the defineMessages API.

How do you access the current locale with React Intl?

Use the useIntl hook or inject it via injectIntl HOC to access intl.locale.

How do you format a date using React Intl?

.

What is the Shallow Renderer in React testing?

It renders a component one level deep without rendering child components, useful for unit testing in isolation.

What is the TestRenderer package in React?

It renders React components to pure JavaScript objects without a DOM, used for snapshot testing (e.g., with Jest).

What is the purpose of the ReactTestUtils package?

It provides utilities to manipulate rendered components and simulate events in a testing environment (often replaced by React Testing Library).

What is Jest?

A JavaScript testing framework created by Facebook, commonly used with React for its zero-config setup and snapshot testing.

What are the advantages of Jest over Jasmine?

Jest is faster (parallel testing), has built-in code coverage, snapshot testing, and requires less configuration.

Can you give a simple example of a Jest test case?

test('adds 1 + 2', () => { expect(1 + 2).toBe(3); });.

What is Flux?

An application architecture for React with unidirectional data flow (Actions -> Dispatcher -> Store -> View).

What is Redux?

A predictable state container for JS apps, inspired by Flux but using a single store and pure reducer functions.

What are the core principles of Redux?

Single source of truth (one store), State is read-only (emit actions), and Changes are made with pure functions (reducers).

What are the downsides of Redux compared to Flux?

Redux can have a steeper learning curve and more boilerplate code due to concepts like reducers and immutability.

What is the difference between mapStateToProps() and mapDispatchToProps()?

mapStateToProps connects Redux state to component props. mapDispatchToProps connects dispatch actions to component props.

Can you dispatch an action in a reducer?

No. Reducers must be pure functions without side effects. Dispatching causes a side effect and an infinite loop.

How do you access the Redux store outside a component?

You can export the store object from your setup file and import it directly to call store.getState() or store.dispatch().

What are the drawbacks of the MVW pattern?

It often leads to bidirectional data flow, making state changes hard to track and debug in complex apps.

Are there any similarities between Redux and RxJS?

Both deal with streams of data/events. Redux is like a single stream of state reductions; RxJS handles complex async streams.

How do you reset state in Redux?

Handle a specific RESET_APP action in your root reducer that returns undefined, causing child reducers to return initial state.

What is the difference between React Context and React Redux?

Context is built-in and good for low-frequency updates (themes). Redux provides devtools, middleware, and performance optimizations for frequent updates.

Why are Redux state functions called reducers?

Because they share the same signature as the callback function passed to Array.prototype.reduce ((accumulator, current) => newAccumulator).

How do you make an AJAX request in Redux?

Use middleware like redux-thunk or redux-saga to handle async logic and dispatch actions on success/failure.

Should you keep all component states in the Redux store?

No. Keep global data (user info, API cache) in Redux. Keep UI state (form inputs, modal open/close) in local component state.

What is the proper way to access the Redux store?

Use the useSelector hook in functional components or the connect HOC in class components.

What is the difference between a component and a container in React Redux?

Presentational components simply render props. Containers connect to Redux to fetch data and dispatch actions.

What is the purpose of constants in Redux?

They prevent typos in action type strings and allow easy refactoring/IDE support (export const ADD_TODO = 'ADD_TODO').

What are the different ways to write mapDispatchToProps()?

As a function (for custom logic) or as an object (shorthand where action creators are automatically wrapped in dispatch).

What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?

It allows you to use the props passed to the wrapper component to influence the state selection or action dispatching logic.

How do you structure Redux top-level directories?

Common patterns include Rails-style (actions, constants, reducers folders) or Feature-based (user folder containing actions/reducer/components).

What is Redux Saga?

A middleware library that uses ES6 Generators to handle side effects (async calls) in a more readable and testable way.

What is the mental model of Redux Saga?

It acts like a separate thread in your application that is solely responsible for side effects.

What are the differences between call and put in Redux Saga?

call runs a function/promise and waits for it (blocking). put dispatches an action to the store (non-blocking).

What is Redux Thunk?

A middleware that allows action creators to return a function instead of an object, enabling async logic inside actions.

What are the differences between Redux Saga and Redux Thunk?

Thunks are simple and use functions/promises. Sagas are more powerful (cancellation, complex flows) but use Generators and are harder to learn.

What is Redux DevTools?

A browser extension that allows you to inspect every state change, time-travel (undo/redo actions), and view action payloads.

What are the features of Redux DevTools?

Time travel debugging, action logging, state diffing, and dispatching actions manually.

What are Redux selectors and why should you use them?

Functions that extract/derive data from the store. They encapsulate state structure and can be memoized (Reselect) for performance.

What is Redux Form?

A library to manage form state in Redux. (Note: It is largely deprecated in favor of React Final Form or Formik).

What are the main features of Redux Form?

Field validation, sync/async validation, submission handling, and persisting form state in the Redux store.

How do you add multiple middlewares to Redux?

Use applyMiddleware(thunk, logger, saga) inside the createStore (or configureStore) function.

How do you set the initial state in Redux?

Pass the initial state object as the second argument to createStore, or define default arguments in reducer functions.

How is Relay different from Redux?

Relay is specifically for fetching data from GraphQL APIs and managing that data. Redux is a generic state manager.

What is an action in Redux?

A plain JavaScript object with a type property (and optional payload) describing an event that happened.

What is the difference between React Native and React?

React renders HTML to the web DOM. React Native renders native UI components (View, Text) to iOS and Android platforms.

How do you test React Native apps?

Use Jest for unit tests, React Native Testing Library for component integration, and Detox/Appium for end-to-end testing.

How do you log in React Native?

console.log works and outputs to the Metro bundler terminal or the browser debugger/React Native Debugger.

How do you debug React Native apps?

Use the In-App Developer Menu, React Native Debugger (standalone app), or Flipper (platform debugging tool).

What is Reselect and how does it work?

A library for creating memoized selectors. It only re-calculates the result if the input arguments change, improving performance.

What is Flow?

A static type checker for JavaScript developed by Facebook, often used with React before TypeScript became dominant.

What is the difference between Flow and PropTypes?

Flow checks types at compile/build time (static). PropTypes checks types at runtime during development.

How do you use Font Awesome icons in React?

Use the react-fontawesome package to render icons as components, e.g., .

What is React DevTools?

A browser extension to inspect the React component hierarchy, view props/state, and profile performance.

Why does DevTools not load in Chrome for local files?

Chrome restricts extensions on file:// protocol. You must enable "Allow access to file URLs" in extension settings or use a local server.

How do you use Polymer in React?

Polymer creates Web Components. React can render these custom elements just like standard HTML tags.

What are the advantages of React over Vue.js?

React has a larger ecosystem, better TypeScript support, and uses JSX (JavaScript power) vs Vue's template syntax.

What is the difference between React and Angular?

React is a library (View only) and flexible. Angular is a full-fledged MVC framework with built-in routing, HTTP, and forms.

Why is the React tab not showing up in DevTools?

It only appears if the website is running a development build of React. Production builds often disable inspection unless configured.

What are styled-components?

A CSS-in-JS library that allows you to write actual CSS code inside JavaScript files to style components using tagged template literals.

Can you give an example of styled-components?

const Button = styled.buttoncolor: red;; .

What is Relay?

A JavaScript framework for building data-driven React applications powered by GraphQL.

What are the main features of the Reselect library?

Memoization (caching results), composition (combining selectors), and efficient recalculation of derived data.

Can you give an example of Reselect usage?

createSelector([getUsers], users => users.filter(u => u.active)) returns a cached list until getUsers changes.

Can Redux only be used with React?

No, Redux is framework-agnostic and can be used with Angular, Vue, vanilla JS, or any other library.

Do you need a specific build tool to use Redux?

No, Redux is just JS. However, build tools are usually needed for the module system (ES6) used in most React/Redux apps.

How do Redux Form initial values get updated from state?

By passing an initialValues prop connected to the Redux state via mapStateToProps.

How do React PropTypes allow different types for one prop?

Use PropTypes.oneOfType([PropTypes.string, PropTypes.number]).

Can you import an SVG file as a React component?

Yes, using Create React App or SVGR, import { ReactComponent as Logo } from './logo.svg' works directly.

What is render hijacking in React?

A pattern (often in HOCs) where the wrapper controls whether and how the wrapped component is rendered.

How do you pass numbers to a React component?

Pass them inside curly braces: .

Do you need to keep all state in Redux? Should you ever use React's internal state?

No. Use Redux for global/shared data. Use React internal state for UI-specific, non-shared data (dropdown open, input hover).

What is the purpose of registerServiceWorker in React?

It was part of Create React App boilerplate to enable PWA features (offline caching) by registering a service worker.

What is the React.memo function?

A higher-order component that memoizes a functional component, skipping re-renders if props don't change.

What is the React.lazy function?

It allows you to render a dynamic import as a regular component, enabling code-splitting.

How do you prevent unnecessary updates using setState?

Check if the new value matches the current state before calling setState, or rely on React's automatic bailout for primitives.

How do you render arrays, strings, and numbers in React v16?

React 16+ can render arrays (returning a list), strings, and numbers directly from the return of a component.

What are Hooks?

Functions that let you "hook into" React state and lifecycle features from function components (e.g., useState, useEffect).

What rules must be followed for Hooks?

Only call Hooks at the top level (not inside loops/conditions) and only call them from React function components or custom Hooks.

How do you ensure Hooks follow the rules in your project?

Use the ESLint plugin eslint-plugin-react-hooks which enforces these rules automatically.

What are the differences between Flux and Redux?

Flux has multiple stores and a dispatcher. Redux has a single store and uses pure reducers instead of a dispatcher.

What are the benefits of React Router v4?

It introduced "Dynamic Routing," where routing takes place as your app is rendering, rather than in a static config configuration.

Can you describe the componentDidCatch lifecycle method signature?

componentDidCatch(error, info). It catches errors in child components and receives the error object and stack trace info.

In which scenarios do error boundaries not catch errors?

They do not catch errors in event handlers, asynchronous code, server-side rendering, or errors thrown in the boundary itself.

What is the behavior of uncaught errors in React v16?

Uncaught errors result in unmounting the entire component tree to prevent displaying corrupted UI.

What is the proper placement for error boundaries?

Place them at the top level to catch generic crashes, or wrap individual widgets to prevent one crash from breaking the whole app.

What is the benefit of a component stack trace from an error boundary?

It shows exactly where in the component tree the error happened, making debugging much easier than a generic JS stack trace.

What are default props?

A property on the component class (or using default parameters in functions) that sets fallback values if props are undefined.

What is the purpose of the displayName class property?

It sets the name of the component used in debugging messages and React DevTools.

What is the browser support for React applications?

React supports all modern browsers. Internet Explorer support was dropped in React 18.

What is code-splitting?

Splitting your bundle into smaller chunks that can be loaded on demand (lazy loading) to improve initial load time.

What are keyed Fragments?

Fragments that have a key attribute. Must use the explicit syntax instead of <>.

Does React support all HTML attributes?

Most, but they are camelCased (e.g., tabIndex). Some attributes like checked behave slightly differently (controlled vs default).

When do component props default to true?

If you pass a prop with no value, it defaults to true. E.g.,

What is Next.js and what are its major features?

A framework for React offering Server-Side Rendering (SSR), Static Site Generation (SSG), file-system routing, and API routes.

How do you pass an event handler to a component?

Pass the function reference as a prop:

More Chapters