React Flashcards
What is Profiler API
A Profiler can be added anywhere in a React tree to measure the cost of rendering that part of the tree. It requires two props: an id (string) and an onRender callback (function) which React calls any time a component within the tree “commits” an update.
render( <App> <Profiler id="Navigation" onRender={callback}> <Navigation {...props} /> </Profiler> <Main {...props} /> </App> );
What methods are called in order during Mounting?
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
What’s the use of a constructor in React?
Initializing local state by assigning an object to this.state.
Binding event handler methods to an instance.
How to prevent props from being undefined in a class component
call super(props)
before any other statement.
Avoid copying props into state.
constructor(props) { super(props); // Don't do this! this.state = { color: props.color }; }
componentDidMount()
componentDidMount()
is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
Where should you place subscriptions in class Components
componentDidMount()
is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount()
.
componentDidUpdate()
componentDidUpdate(prevProps, prevState, snapshot)
is invoked immediately after updating occurs. This method is not called for the initial render. Compare prev and current props before making data requests/calculations, to prevent infinite loops.
Cases where componentDidUpdate()
is not invoked?
componentDidUpdate()
will not be invoked if shouldComponentUpdate()
returns false.
componentWillUnmount()
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Do necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount()
.
shouldComponentUpdate()
Use shouldComponentUpdate()
to let React know if a component’s output is not affected by the current change in state or props.
This method only exists as a performance optimization. Do not rely on it to “prevent” a rendering, as this can lead to bugs. Consider using the built-in PureComponent
instead of writing shouldComponentUpdate()
by hand. PureComponent performs a shallow comparison of props and state, and reduces the chance that you’ll skip a necessary update.
static getDerivedStateFromProps()
getDerivedStateFromProps
is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate()
is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle method will be passed as a parameter to componentDidUpdate()
.
static getDerivedStateFromError()
This lifecycle is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.
static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true }; }
componentDidCatch()
This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters:
error
- The error that was thrown.info
- An object with a componentStack key containing information about which component threw the error.
What are the legacy Lifecycle Methods
componentWillMount
componentWillReceiveProps
componentWillUpdate
How to work with legacy Lifecycle Methods
adding the following lifecycle aliases: UNSAFE_componentWillMount
, UNSAFE_componentWillReceiveProps
, UNSAFE_componentWillUpdate
.
using, static getDerivedStateFromProps
and getSnapshotBeforeUpdate
.
render()
The render()
is the only required method in a class component.
When called, it should examine this.props
and this.state
and return one of the following types:
React elements. Typically created via JSX. For example, <div />
and <MyComponent />
are React elements that instruct React to render a DOM node, or another user-defined component, respectively.
Arrays and fragments. Let you return multiple elements from render.
Portals. Let you render children into a different DOM subtree.
String and numbers. These are rendered as text nodes in the DOM.
Booleans or null. Render nothing. (Mostly exists to support return test && <Child />
pattern, where test is boolean.)
In what occasion will render()
not be invoked?
render()
will not be invoked if shouldComponentUpdate()
returns false.
setState()
setState(updater[, callback])
Updates state by merging the whole state with the individual piece of state updated.
forceUpdate()
component.forceUpdate(callback)
By default, when your component’s state or props change, your component will re-render. If your render()
method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate()
.
defaultProps
defaultProps
can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined
props, but not for null
props.
displayName
The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component.
What is the meaning of Virtual DOM?
The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.
Can browsers read a JSX file?
No, browsers cannot read JSX files directly. It can only read the objects provided by JavaScript. Now, to make a browser read a JSX file, it has to be transformed to a JavaScript object using JSX transformers, and only then it can be fed into the browser for further use in the pipeline.
What are higher-order components (HOCs) used for?
HOCs are used for a variety of tasks such as:
- Manipulation of props
- State manipulation and abstraction
- Render highjacking
- Code reusing
- Bootstrap abstraction
What is React Fiber?
Fiber is the new reconciliation engine in React 16. Its main goal is to enable incremental rendering of the virtual DOM.
Why do we need to transpile
React code?
React code is written in JSX, but no browser can execute JSX directly as they are built to read-only regular JavaScript.
Thus we require to use tools like Babel to transpile JSX to JavaScript so that the browser can execute it.
What is Webpack
webpack is a static module bundler for modern JavaScript applications.
When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from
What is the significance of keys
in React?
Keys in React is used to identify unique VIRTUALDOM Elements with their corresponding data driving the UI; having them helps React optimize rendering by recycling existing DOM elements.
Key helps React identify which items have changed, are added, or are removed, enabling it to reuse already existing DOM elements, thus providing a performance boost.
What is the significance of refs
in React?
Refs are variables that allow you to persist data between renders, just like state variables, but unlike state variables, updating refs does NOT cause the component to re-render.
Refs are usually used to, but not restricted to, store reference to DOM elements.
What are the most common approaches for styling a React application?
- CSS Classes
- Inline CSS
- Pre-processors (Sass, Stylus, and Less)
- CSS-in-JS Modules (Styled Components, Emotion, and Styled-jsx)
What are some of the performance optimization strategies for React?
- useMemo
- useCallback
- Lazy Loading
What is prop drilling and how to avoid it?
Sometimes while developing React applications, there is a need to pass data from a component that is higher in the hierarchy to a component that is deeply nested. To pass data between such components, we pass props from a source component and keep passing the prop to the next component in the hierarchy till we reach the deeply nested component.
What are the Pointer Events supported in React?
onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut
What is the StrictMode
component and why would you use it?
<StrictMode></StrictMode>
is a component included with React to provide additional visibility of potential issues in components. Suppose the application is running in development mode. In that case, any issues are logged to the development console, but these warnings are not shown if the application is running in production mode.
What are synthetic events
in React?
Synthetic events
combine the response of different browser’s native events into one API, ensuring that the events are consistent across different browsers. The application is consistent regardless of the browser it is running in.
Why is it not advisable to update state directly, but use the setState
call?
The conventional way to update state is to use the setState call. Without using it, the user would still be able to modify the state, but it would not update the DOM to reflect the new state.
What are portals in React?
Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
const Portal = ({ children }) => { // NOTE: it is advisable to create a new DOM node for the portal const portalRoot = document.getElementById("portal-root"); return ReactDOM.createPortal(children, portalRoot); };
What are the differences between a Class component and Functional component?
**Class Components
**
* Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.
* Class components extend from React.Component
.
* In here you have to use this
keyword to access the props and functions that you declare inside the class components.
** Functional Components
**
* Functional Components are simpler comparing to class-based functions.
* Functional Components mainly focuses on the UI of the application, not on the behavior.
* To be more precise these are basically render function in the class component.
* Functional Components can have state and mimic lifecycle events using Reach Hooks
What’s debouncing
in React
Debouncing enforces that a function won’t be called again until a certain amount of time has passed without it being called.
export const debounce = (func, delay) => { let debounceHandler; return function () { const context = this; const args = arguments; clearTimeout(debounceHandler); debounceHandler = setTimeout(() => func.apply(context, args), delay); }; };
What’s throttling
in React?
Throttling enforces a maximum number of times a function can be called over time.
export const throttle = (func, limit) => { let inThrottle; return function () { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }; };
useMemo vs useCallback
To be done by Mildred