React basics
React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
Data flow - One way only - Top to bottom
React components can have props (Attributes/Values that provided by parent) and state (This is data that's maintained by current component).
Few things to note:- Props are read-only. Props should never be changed in a child component, so if there’s something going on that alters some variable, that variable should belong to the component state.
- Do Not Modify State Directly Modifying state directly
won't result in component re-render. State by itself is just an object.
So, use either hooks or
setState()
method - React updates are asynchronous. Being asynchronous in nature allows React the ability to batch multiple update events either through update of props or state updates.
Virtual DOM
Virtual Document Object Model React creates an in-memory data structure cache which of the corresponding element. Virtual DOM uses a very light weight representation of actual DOM and updates only the items in the Real DOM that were changed, instead of re-rendering entire DOM tree again.
Reconciliation & Rendering
- Render phase
- Commit phase
Render phase
This phase takes in JSX, current & updated values to create a representation of the updated HTML state/structure.
- On initial rendering, it takes your JSX and turns it into a javascript representation of what the HTML structure should look like.
- On updates after the Virtual DOM is created & rendered initiallys, React will compare what it has built out to what the actual DOM has using a it's diffing algorithm.
Note: React goes through its virtualDOM and creates a list of those changes that need to be made to the actual DOM . Meaning that React will wait to commit all the updates so it does it in one process and not in parts. This is how React does batch updates. This is crucial to understand when working with state.
In Re-rendering, it does not go through every component to check for updates. Instead, when your component state or props update React uses a flag to mark that component. Basically saying that this component has been marked for an update.
Commit phase
The commit phase is actually taking that representation and applying it to the real DOM.
React Fiber
- Incremental Rendering: React Fiber introduces the concept of incremental rendering, where the work of rendering a component tree is broken down into smaller chunks or "fibers." This allows React to prioritize and schedule work more efficiently, enabling better responsiveness and smoother user experiences.
- Priority Scheduling: React Fiber enables developers to assign priorities to different types of updates, allowing more critical updates to be processed before less critical ones. This helps ensure that high-priority tasks, such as user interactions or animations, are handled promptly, improving perceived performance.
- Suspense and Error Boundaries: React Fiber introduces the concept of Suspense, which allows components to suspend rendering while waiting for asynchronous data to load. This feature enables better handling of loading states and code-splitting scenarios. Error boundaries are also enhanced in React Fiber, providing better error handling and recovery mechanisms.
- Improved Rendering Pipeline: React Fiber refines the rendering pipeline, making it more predictable and efficient. It enables better support for concurrent rendering, allowing React to work on multiple tasks simultaneously without blocking the main thread.
- Better Debugging and Profiling Tools: React Fiber provides improved debugging and profiling capabilities, allowing developers to better understand the performance characteristics of their applications and identify areas for optimization.
Keys in lists
key is a special attribute that you need to include in the element, and it should be a string. Keys in each list should be unique, which means that you should not use values that can be the same as the key. In other words, keys should be unique among the siblings, not globally.
This is used by react to identify elements in list.
How is diffing between two trees so fast ?
TODO
What are SyntheticEvents
and why use them ?
React synthetic events mirror browser native events very closely & are built upon them. This is so that the same API interface can be used for implementation across different browsers & react runtimes.
You can always access native events with the nativeEvent attribute if you need direct access . React, however, pools SyntheticEvent objects between all events, meaning that there is only one active SyntheticEvent object at a time. When an event is triggered, the properties of the SyntheticEvent object are set using the browser native event. The SyntheticEvent object is then passed to your callback function. Once the callback function is complete, the SyntheticEvent object will be nullified (all its properties will be reset to null) so that it can be reused by the next event handler.
As well as only having one SyntheticEvent object, React only has one event listener. React employs top-level event delegation. Rather than attach an event listener to each DOM node that we specify, React creates a single, top-level event listener that can capture all native browser events. When we mount and unmount a component in which we have specified some event handling, this is just added to the internal mapping of the top-level event listener. For further see [Ref]
tldr; Performance & cross-browser implementation
Different kinds of React components
- Functional component : This is a simple function that accepts a single “props” object argument with data and returns a React element.
- Class component : Similar to functional component in
terms what it does by extends
React.Component
class. - Pure component : (Not really considered a different variant
but had some interviewers ask this as such) This is similar to
React.Component
but implementsshouldComponentUpdate()
method with shallow comparison of state & props . This helps the rendering to be optimized as it skips re-rendering of components if there is no change of props and state.
What is a side-effect ?
A "side effect" is anything that affects something outside the scope of the function being executed. These can be, say, a network request, which has your code communicating with a third party (and thus making the request, causing logs to be recorded, caches to be saved or updated, all sorts of effects that are outside the function.
There are more subtle side effects, too. Changing the value of a closure-scoped variable is a side effect. Pushing a new item onto an array that was passed in as an argument is a side effect. Functions that execute without side effects are called "pure" functions: they take in arguments, and they return values. Nothing else happens upon executing the function. This makes the easy to test, simple to reason about, and functions that meet this description have all sorts of useful properties when it comes to optimization or refactoring.
React error boundaries
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
A class component becomes an error boundary if it defines either (or
both) of the lifecycle methods static getDerivedStateFromError()
or componentDidCatch()
. Use static getDerivedStateFromError() to render a fallback UI after an
error has been thrown. Use componentDidCatch() to log error information.
How is different from Angular ?
React primarily is library meant to handle view part i.e., primarily focuses on rendering the UI. Angular on the other hand is a more comprehensive framework for building webapps. It encompasses entire plethora of MVC architecture.
React as mentioned previously follows one way binding (top-to-bottom] data flow whereas Angular allows for one-way and two-way binding i.e., model and view synchronize the data they're bound to.
What is react virtualization ?
The main concept behind virtual rendering is rendering only what is visible. Larger number of DOM nodes bring downt the page w.r.t to performance and usability. So it makes sense to load only the elements that are visible and unload them when they are not by replacing them with new ones.
References:
- React State and Lifecyclehttps://reactjs.org/docs/state-and-lifecycle.html
- React way of thinkinghttps://reactjs.org/docs/thinking-in-react.html
- When to use forceUpdate() in React ⚛https://dev.to/harshilparmar/when-to-use-forceupdate-in-react-464d
- Wild React 🦒: useForceUpdate()https://medium.com/@dev.cprice/wild-react-useforceupdate-e4459f2c1272
- React pure componenthttps://reactjs.org/docs/react-api.html#reactpurecomponent
- When is it a good idea to work with React Pure Components?https://medium.com/technofunnel/working-with-react-pure-components-166ded26ae48
- React JS Higher-Order Components descriptionhttps://reactjs.org/docs/higher-order-components.html
- A simple for-dummies kind of explaination on React synthetic eventshttps://blog.logrocket.com/getting-started-react-synthetic-event/
- Synthetic Events in Reacthttps://medium.com/@maxfpowell/synthetic-events-in-react-a95e6dc80c99
- Understanding Reconciliation: React Rendering Phaseshttps://dev.to/thee_divide/reconciliation-react-rendering-phases-56g2
- Good explaination in a reddit thread about side effects by user vcarlhttps://www.reddit.com/r/reactjs/comments/8avfej/what_does_side_effects_mean_in_react/
- React fiber architecturehttps://github.com/acdlite/react-fiber-architecture