Source: javascript.info
38 |JavaScript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks. This model is quite different from models in other languages like C and Java.
46 |Function calls form a stack of frames.
49 |50 | 51 | function foo(b) { 52 | let a = 10 53 | return a + b + 11 54 | } 55 | 56 | function bar(x) { 57 | let y = 3 58 | return foo(x * y) 59 | } 60 | 61 | console.log(bar(7)) //returns 42 62 |
63 |64 | When calling bar, a first frame is created containing bar's arguments and local variables. When bar calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables. When foo returns, the top frame element is popped out of the stack (leaving only bar's call frame). When bar returns, the stack is empty. 65 |
66 |68 | Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory. 69 |
70 |72 | A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function which gets called in order to handle the message. The processing of functions continues until the stack is once again empty. Then, the event loop will process the next message in the queue (if there is one). 73 |
74 |76 | The event loop got its name because of how it's usually implemented, which usually resembles: 77 |
78 |79 | 80 | while (queue.waitForMessage()) { 81 | queue.processNextMessage() 82 | } 83 |
84 |85 | queue.waitForMessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled). 86 |
87 |Source: MDN web docs
88 |96 | A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. 97 |
98 |Every closure has three scopes:
99 |105 | A common mistake is not realizing that, in the case where the outer function is itself a nested function, access to the outer function's scope includes the enclosing scope of the outer function—effectively creating a chain of function scopes. To demonstrate, consider the following example code. 106 |
107 |108 | 109 | // global scope 110 | var e = 10; 111 | function sum(a){ 112 | return function(b){ 113 | return function(c){ 114 | // outer functions scope 115 | return function(d){ 116 | // local scope 117 | return a + b + c + d + e; 118 | } 119 | } 120 | } 121 | } 122 | 123 | console.log(sum(1)(2)(3)(4)); // log 20 124 | 125 | // You can also write without anonymous functions: 126 | 127 | // global scope 128 | var e = 10; 129 | function sum(a){ 130 | return function sum2(b){ 131 | return function sum3(c){ 132 | // outer functions scope 133 | return function sum4(d){ 134 | // local scope 135 | return a + b + c + d + e; 136 | } 137 | } 138 | } 139 | } 140 | 141 | var s = sum(1); 142 | var s1 = s(2); 143 | var s2 = s1(3); 144 | var s3 = s2(4); 145 | console.log(s3) //log 20 146 |
147 |148 | In the example above, there's a series of nested functions, all of which have access to the outer functions' scope. In this context, we can say that closures have access to all outer function scopes. 149 |
150 |Source: MDN web docs
151 |159 | A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode. 160 |
161 |Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. 168 | 169 | function f1() { 170 | return this; 171 | } 172 | 173 | // In a browser: 174 | f1() === window; // true 175 | 176 | // In Node: 177 | f1() === globalThis; // true 178 | 179 |
180 |181 | In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined. 182 | 183 | function f2() { 184 | 'use strict'; // see strict mode 185 | return this; 186 | } 187 | 188 | f2() === undefined; // true 189 |
190 |Source: MDN web docs
199 |207 | The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. 208 |
209 |210 | A Promise is in one of these states: 211 |
212 |224 | A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. 225 |
226 |227 | As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained. 228 |
229 |
230 | 231 | The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. These methods also return a newly generated promise object, which can optionally be used for chaining; for example, like this: 232 | 233 | const myPromise = 234 | (new Promise(myExecutorFunc)) 235 | .then(handleFulfilledA,handleRejectedA) 236 | .then(handleFulfilledB,handleRejectedB) 237 | .then(handleFulfilledC,handleRejectedC); 238 | 239 | // or, perhaps better ... 240 | 241 | const myPromise = 242 | (new Promise(myExecutorFunc)) 243 | .then(handleFulfilledA) 244 | .then(handleFulfilledB) 245 | .then(handleFulfilledC) 246 | .catch(handleRejectedAny); 247 |
248 |Source: MDN web docs
249 |
316 | Source: reactjs.org
317 |Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
325 |Using context, we can avoid passing props through intermediate elements:
326 |
327 | // Context lets us pass a value deep into the component tree
328 | // without explicitly threading it through every component.
329 | // Create a context for the current theme (with "light" as the default).
330 | const ThemeContext = React.createContext('light');
331 |
332 | class App extends React.Component {
333 | render() {
334 | // Use a Provider to pass the current theme to the tree below.
335 | // Any component can read it, no matter how deep it is.
336 | // In this example, we're passing "dark" as the current value.
337 | return (
338 |
Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.
366 |Source: reactjs.org
385 |393 | 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. 394 |
395 |396 | In React world, the term “virtual DOM” is usually associated with React elements since they are the objects representing the user interface. React, however, also uses internal objects called “fibers” to hold additional information about the component tree. They may also be considered a part of “virtual DOM” implementation in React. 397 |
398 |Source: reactjs.org
399 |407 | Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity 408 |
409 |410 | The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys 411 |
412 |413 | When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort. We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. 414 |
415 |Source: reactjs.org
416 |424 | Some components don’t know their children ahead of time. This is especially common for components like Sidebar or Dialog that represent generic “boxes”. We recommend that such components use the special children prop to pass children elements directly into their output: 425 |
426 |427 | 428 | function FancyBorder(props) { 429 | return ( 430 |
437 | This lets other components pass arbitrary children to them by nesting the JSX: 438 |
439 |
440 |
441 | function WelcomeDialog() {
442 | return (
443 |
448 | Thank you for visiting our spacecraft!
449 |
445 | Welcome
446 |
447 |
455 | Anything inside the
Source: reactjs.org
458 |467 | In HTML, form elements such as input, textarea, and select typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState(). 468 |
469 |470 | We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”. 471 |
472 |473 | To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM. 474 |
475 |476 | Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components. 477 |
478 |Source: 479 | reactjs.org, 480 | reactjs.org 481 |
482 |490 | React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison. 491 |
492 |493 | If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases. 494 |
495 |496 | React.PureComponent’s shouldComponentUpdate() only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences. Only extend PureComponent when you expect to have simple props and state, or use forceUpdate() when you know deep data structures have changed. Or, consider using immutable objects to facilitate fast comparisons of nested data. Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”. 497 |
498 |Source: 499 | reactjs.org 500 |
501 |509 | A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature. 510 |
511 |512 | Concretely, a higher-order component is a function that takes a component and returns a new component. 513 | 514 | const EnhancedComponent = higherOrderComponent(WrappedComponent); 515 |
516 |517 | HOCs are common in third-party React libraries, such as Redux’s connect and Relay’s createFragmentContainer. 518 |
519 |Source: 520 | reactjs.org 521 |
522 |530 | Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Hooks don’t work inside classes. But you can use them instead of writing classes. 531 |
532 |533 | A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components: 534 | 535 | import React, { useState } from 'react'; 536 | 537 | function Example() { 538 | // Declare a new state variable, which we'll call "count" 539 | const [count, setCount] = useState(0); 540 | 541 | return ( 542 |
You clicked {count} times
544 | 547 |552 | It declares a “state variable”. Our variable is called count but we could call it anything else, like banana. This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React. The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need. In our example, we just want a number for how many times the user clicked, so pass 0 as initial state for our variable. (If we wanted to store two different values in state, we would call useState() twice.). It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(). 553 |
554 |555 | The Effect Hook lets you perform side effects in function components: 556 | 557 | import React, { useState, useEffect } from 'react'; 558 | 559 | function Example() { 560 | const [count, setCount] = useState(0); 561 | 562 | // Similar to componentDidMount and componentDidUpdate: 563 | useEffect(() => { 564 | // Update the document title using the browser API 565 | document.title = `You clicked ${count} times`; 566 | }); 567 | 568 | return ( 569 |
You clicked {count} times
571 | 574 |579 | By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API. Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We don’t need a special API to read it — it’s already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution. By default, it runs both after the first render and after every update. Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects. 580 |
581 |582 | useContext 583 | 584 | const value = useContext(MyContext); 585 |
586 |
587 | Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest
Source: 590 | reactjs.org 591 |
592 |604 | HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the foundation of any data exchange on the Web and it is a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more. 605 |
606 |
607 | 608 | Here is a list of common features controllable with HTTP: 609 |
610 |Source: MDN web docs
629 |