React
A declarative library to build web and native UI.
- Renderables: react element, arrays, fragments, portals, JS primtives. Boolean and Nullish are rendered as empty nodes.
- Component : Encapsulate one piece of UI. It’s a class/factory function for a React Element. Rendering a component means creating an instance
- Root : top-level element that is root of React render tree. Used as entry point to takeover DOM handling. Two methods:
createRoot and hydrateRoot
- Keys : how react identifies position of element in render tree. If key changes, component remounts. Each sibling in a list must have unique constant key
- Portals : To render React element into any random DOM node. Only changes the physical placement, but not behaviour (bubbling etc.)
Data categories
- Props: immutable object used by components to pass data down. To communicate up, use callback props OR render props
- State: a component's private mutable data that triggers re-renders. Source of truth for UI.
- Refs :
- objects that persist values across re-renders without triggering a re-render
- Unlike state, ref updates are synchronous. Provide a way to access DOM for vanilla manipulation
- Ref callback : callback passed to
refcalled when React attaches/detaches the node (node/null) or when fn object changes
- setters can be safely used as refcb, since setter is stable
- Context: provides a way to share data across a sub-tree without prop drilling (forwarding props in every component from source to target)
//without JSX (syntax sugar)
React.createElement('h1', { title:'heading', onClick: handler }, 'hello');
//Portals
<div>
{createPortal(<Tool/>, $('.tool'), key?)}
</div>
Virtual DOM
- a lightweight in-memory representation of actual DOM kept by React
- created on each trigger and compared with previous VDOM to reconciliate
- Diffing algorithm (O(n)) : uses BFS-search. If nodes are referentially same, they are considered equal (
Object.is() strategy ).