React Frequently Asked Questions

Brush up on these core (and some tricky) React concepts before your next interview.What is the virtual DOM?Updating the DOM and repainting the UI is expensive, so React uses a virtual representation of the real DOM, kept in memory and synced with the r…

Brush up on these core (and some tricky) React concepts before your next interview.

What is the virtual DOM?

Updating the DOM and repainting the UI is expensive, so React uses a virtual representation of the real DOM, kept in memory and synced with the real DOM, to optimize the changes needed and improve the performance of the application.

Whenever the UI is updated with new elements, a new virtual DOM is created to represent the new tree.

This is then compared or “diffed” with the previous version of the tree to find the best possible way to update the real DOM. Updates to the real DOM are also sent in batches for increased performance and repainting efficiency.

What are keys?

Keys are special string attributes passed to elements in a list, so React can correctly identify which items in the list were changed, updated or deleted.

They need to be unique among siblings and using list indexes is highly discouraged, as reordering the list would mess up the keys and result in unpredictable behavior — instead, use a unique element ID.

Can I change the state variable directly without using the update function returned by useState?

Well, you can, but you shouldn’t. Changing the value directly does not trigger a re-render so you won’t see any UI changes. Now, if the state variable is a primitive value (undefined, null, boolean, number, bigint, string, symbol) any direct mutations to it will be overwritten on the next render by the useState hook.

If the state variable is an object, you can mutate its contents since you have its memory reference.

This still won’t trigger a re-render, but you may see these changes on the next render, making this method extremely unreliable and leading to tricky bugs.

Are there any cases where updating a state variable might not trigger a re-render?

React uses the Object.is comparison algorithm to compare previous and new state values and decide if a re-render should be triggered.

The algorithm pretty much works like a triple equal (===) comparison so, updating the state with the same state value (primitive value or object reference) will not trigger a re-render (note a few differences with the treatment of signed zeroes and NaNs between Object.is and triple equal).

What is prop drilling, and how can I avoid it?

It is the process by which data is passed through several levels of components in the hierarchy, going through parts of the application that have no use for it.

There is nothing inherently bad in this pattern, but it’s a bad practice: data is accessed by unrelated components, components become tightly coupled, unnecessary re-renders are triggered along the chain of props, and the code is harder to maintain.

A common approach to solving this issue is using the Context API. You define a Provider component that supplies data to nested components that consume it through a Consumer component or the useContext hook.

What are controlled and uncontrolled components? When should I use each one?

When handling user input, there are two main approaches in the way you manipulate the value. In a controlled component, you store the value as state and sync it through event-based callbacks, like onChange.

This is a good approach if you want to validate, apply a custom mask or update the DOM as the value changes.

On the contrary, with uncontrolled components, you let the value be handled by the DOM itself, just like normal HTML form elements, and have access to it through the component’s ref attribute.

For most use cases, a controlled component is the best option, but it can be an overkill if the form is simple and you don’t need instant validation, or if validation happens when the form is submitted and you don’t have any other fields depending on the value of the input.

useEffect: when are effects fired? What about clean-up functions?

Effects run after the render is committed (layout and painting). By default, effects fire after each render.

You can pass an array of values as the hook’s second argument to conditionally fire the effect every time one of these changes. If the array is empty, the effect will be executed only once: after the component is mounted and rendered for the first time.

Clean-up functions always run after the next render and before the next effect is fired, cleaning the previous effect before running the next one. When the component unmounts, its clean-up function is executed one last time.

What’s a closure?

It’s a function that remembers where it was created and can access its outer variables or lexical environment.

In other words, it gives you access to the outer scope. In JavaScript, all functions are naturally closures, maintaining a hidden reference to their outer environment. One example of a closure is a function that returns another function.

Counter implemented with a closure.

What’s a stale closure? How does it relate to useEffect?

It’s a closure that captures variables that have outdated values.

Stale closure

In the example above, the closure has captured the value of message with the initial value of count and, since it’s not updated, its value will remain through successive calls. This can be solved by updating the message variable inside the function returned, so count will be reread on each execution of it.

In a React application, stale closures can happen when setting a timer function inside an effect with an incomplete array of dependencies. If the timer’s callback function reads state variables or props, then it should be reset on each mutation.

useEffect stale closure log.

How can I validate props?

PropTypes is a runtime type-checking tool for props in React applications. You can use prop-types to document the intended types of properties passed to components.

When a component receives a prop of a different type or shape, or a required prop is missing, you will see a warning in the console. Validation is only performed in development, you will not get any warnings in production.

PropTypes runtime type-checking error.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript — it offers all of JavaScript’s features, and an additional type system on top of these. Type-checking is performed at compile time.

The main benefit of TypeScript is that it can highlight unexpected behavior in the code, lowering the chance of bugs.

TypeScript compile-time type-checking error.

What is strict mode?

ECMAScript 5 has a strict mode that results in cleaner JavaScript, with fewer unsafe features, more warnings, and more logical behavior. The normal (non-strict) mode is sometimes called “sloppy mode”.

To invoke strict mode on a JS script, write“use strict”; at the top of the file or before a line. In ECMAScript 2015, classes and modules already enable use strict automatically.

Strict mode modifies syntaxis and behavior on run-time, treating all mistakes as errors, so they can be easily identified and fixed. E.g: makes it impossible to create global variables by accident — in non-strict mode, if the name of a variable is misspelled on an assignment, JS will create a new global variable with that name.

In non-strict mode, assignments to undefined, Infinity, read-only, getters, non-extensible properties will fail silently.

In a React application, StrictMode helps to identify unsafe, legacy or deprecated APIs/lifecycles. Since it’s a developer tool, it runs only in development mode, so it won’t have an impact on the production build.

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favourite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components.

Give it a try →

Learn more


React Frequently Asked Questions was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


Print Share Comment Cite Upload Translate
APA
Leandro Ercoli | Sciencx (2024-03-28T09:28:26+00:00) » React Frequently Asked Questions. Retrieved from https://www.scien.cx/2022/05/03/react-frequently-asked-questions/.
MLA
" » React Frequently Asked Questions." Leandro Ercoli | Sciencx - Tuesday May 3, 2022, https://www.scien.cx/2022/05/03/react-frequently-asked-questions/
HARVARD
Leandro Ercoli | Sciencx Tuesday May 3, 2022 » React Frequently Asked Questions., viewed 2024-03-28T09:28:26+00:00,<https://www.scien.cx/2022/05/03/react-frequently-asked-questions/>
VANCOUVER
Leandro Ercoli | Sciencx - » React Frequently Asked Questions. [Internet]. [Accessed 2024-03-28T09:28:26+00:00]. Available from: https://www.scien.cx/2022/05/03/react-frequently-asked-questions/
CHICAGO
" » React Frequently Asked Questions." Leandro Ercoli | Sciencx - Accessed 2024-03-28T09:28:26+00:00. https://www.scien.cx/2022/05/03/react-frequently-asked-questions/
IEEE
" » React Frequently Asked Questions." Leandro Ercoli | Sciencx [Online]. Available: https://www.scien.cx/2022/05/03/react-frequently-asked-questions/. [Accessed: 2024-03-28T09:28:26+00:00]
rf:citation
» React Frequently Asked Questions | Leandro Ercoli | Sciencx | https://www.scien.cx/2022/05/03/react-frequently-asked-questions/ | 2024-03-28T09:28:26+00:00
https://github.com/addpipe/simple-recorderjs-demo