Let's talk about the conclusion first useCallback, useMemo, memo, shouldUpdate, performance optimized API, you should not use it without performance problems. Blind use will lead to negative optimization and even delay closure bug. This conclusion is a consensus. but this is only one aspect. I mainly want to talk about it to the point, except for the ideas that API,React really reduces rerender. the coarse granularity of React may hurt innocent people. The agility of jsx, the culprit, makes it difficult for props to distinguish between change and immutability App is a component and Box is a subcomponent const App = ()=>{ return <Box h="200px" w="200px" {/*.....*/}>hello</Box> } // after jsx is compiled const App = ()=>{ return /*#__PURE__*/ React.createElement(Box, { h: "200px", w: "200px" }, "hello"); }; The strategy adopted by React is congruent comparison. Props compares {h: "200px", w: "200px"} in the first time with {h: "200px", w: "200px"} in the second round. Although it seems to be the same, function creates a new object type every time, with a different address, rendering even empty objects, like flood discharge, rendering from the top of the head to the soles of the feet. Box will be rendered const App = () => { return <Box>hello</Box> // Box without memo, still render } // after jsx is compiled const App = () => { // props is an empty object here return /*#__PURE__*/ React.createElement(Box, {}, "hello"); }; this is React's App-level update policy. Why do you adopt such a strategy? Because there are too many props, suppose it is a…

May 31, 2023 0comments 1189hotness 0likes Aaron Read all

set up the environment every time you start a job or buy a new computer. Here are some of my essential software tools raycast www.raycast.com/   this is an efficiency tool on macOS. The body looks like this, similar to the native Spotlight, but it has a lot of features and third-party plug-ins. personal frequently used functions are: Software preset: Open APP, the most basic function File Search-File search Calculator-enter the formula in the input box to automatically calculate Coin conversion-enter the corresponding currency, such as 100usd Window Management-split, window management (instead of Rectangle) clipboard history-pasteboard history Snippets-Quick input fixed vocabulary it is easier to use third-party plug-ins: Easydict-look up words, translate IP-Geolocation-query IP View 2FA Code-SMS verification code (by reading iMessage) the above commonly used instructions I will add personal keyboard shortcuts to call, reducing the use of steps. notion www.notion.so/product this is an All-in-one note-taking tool with many templates built into it, including bookkeeping, reminders, etc., basically covering all aspects of life. at present, I am mainly used to record some ideas and summarize the knowledge system. Command Line iterm2 iterm2.com/ Mac command line tools, some keyboard shortcuts and display effects are better than native terminal, and are used to it. zsh & oh my zsh ohmyz.sh/#install provides command line beautification, syntax highlighting and automatic completion, and many convenient shortcut instructions can be added through plug-ins for example, there are gst, gco and other short commands in the git plug-in to facilitate input in addition, you can adjust the theme of the interface according to your personal preferences…

May 30, 2023 0comments 1273hotness 0likes Aaron Read all

there have been various disputes over front-end framework for a long time. The most controversial items are the following two: performance dispute dispute over API design for example, emerging frameworks come up with benchmark to prove their excellent runtime performance, and React is usually at the bottom of these benchmark . in the API design, Vue enthusiasts believe that "more API constrains developers and will not cause significant differences in code quality due to differences in the level of team members." and React enthusiasts think: " Vue a large number of API limits flexibility, JSX yyds". the above discussion boils down to the trade-off between framework performance and flexibility. this article introduces a state management library called legendapp , which is very different from other state management libraries in terms of design philosophy. rational use of legendapp in React can greatly improve the runtime performance of the application. but the purpose of this article is not just to introduce a state management library, but to share with you changes in framework flexibility as performance improves. performance optimization of React It is an indisputable fact that the performance of React is really not very good. The reason is the top-down update mechanism of React . with each status update, React traverses the entire component tree first, starting from the root component. since the traversal mode is fixed, how do you optimize performance? The answer is looking for subtrees that can be skipped when traversing . what kind of subtree can skip traversal? Obviously a subtree of that hasn't changed. in React…

May 29, 2023 0comments 1245hotness 0likes Aaron Read all

there are three front-end framework concepts that are easily confused: responsive updates unidirectional data flow Bidirectional data binding before continuing with this article, readers can think about whether they clearly know the meaning of the three. these three are easy to be confused because although they belong to the same front-end framework, they are not the same level of abstraction, so it is difficult to compare them directly. this article will explain the differences between these three levels of abstraction. responsive updates responsive update is also called fine-grained update . At the same time, the recently popular concept of Signal describes responsive updates . In a nutshell, responsive update describes the relationship between state and UI , that is, how state changes map to UI changes . consider the following example (from what are signals article): function TodoApp() { const [todos, setTodos] = useState( [{ text: 'sleep', completed: false }] ) const [showCompleted, setShowCompleted] = useState(false) const filteredTodos = useMemo(() => { return todos.filter((todo) => !todo.completed || showCompleted) }, [todos, showCompleted]) return ( <TodoList todos={filteredTodos} /> ) } in the TodoApp component, two states are defined: to-do todos whether to show completed items showCompleted and the state derived from the above state filteredTodos . Finally, the & lt;TodoList/> component is returned. if the state of todos changes, how does UI change? That is, how do we know the scope of influence of state changes ? At this point, there are two ideas: push ( push ) pull ( pull ) the principle of push We can start with the changing…

May 27, 2023 0comments 1207hotness 0likes Aaron Read all

there is a sentence that I believe everyone has heard: the replacement of instant noodles is not the more advanced instant noodles, but the rise of takeout the same phenomenon exists in the front-end domain. As a leader in the front-end cache, React-Query has always had a large audience, and the official React-Query courses have sold 8w + copies. but it is such a hit product that there is a risk of being eliminated. Why on earth? Nature of the front-end cache React-Query is located as front-end cache . If you understand the library from a front-end perspective, you might think of it as an enhanced version of axios . but to understand the nature of this library, we need to start from a back-end perspective. in the view of the back end, the back end is responsible for providing the data, and the front end is responsible for displaying the data, so: how should the front end render after the data is updated? After data invalidation, how should the front end render? In essence, this is a data / cache synchronization problem, but in the SPA era, this problem happens to be left to the front end. however, the back end is inherently closer to the data, and it has an advantage to solve this problem. So as rendering tasks gradually move to the back end, React-Query (or similar libraries) gradually lose market. To sum up: what replaces React-Query is not a more advanced competition, but that the soil in which it exists is gradually disappearing. change of SSR…

May 26, 2023 0comments 1417hotness 0likes Aaron Read all

in React applications, as the number of components increases, so does the size of the application. This may cause the application to load for too long and bring a bad experience to the user. To solve this problem, we can use component-level demand loading. On-demand loading can improve application performance, reduce page loading time, and improve user experience. In this blog post, I will detail how to implement component-level on-demand loading in React. what is demand loading? on-demand loading (also known as lazy loading) is a technique that allows us to delay loading code until it really needs to be executed. In React applications, demand loading allows us to load components or other resources dynamically when needed, rather than when they are initially loaded. This means that applications can start faster, reduce unnecessary network requests and file sizes, and improve performance and response speed. Why use demand loading? the main reason for using demand loading in React applications is to improve performance and user experience. When we use demand loading, we only load code when needed, not all code when the application starts. This can reduce page loading time and network requests, and improve application response speed and user satisfaction. In addition, demand loading can reduce the file size of the application because we only need to load the necessary code and resources. implementation of demand loading React supports a variety of ways to load components on demand, including using React.lazy and Suspense API, using higher-level components, and using dynamic imports. Now I will introduce the usage of each method…

May 25, 2023 0comments 1573hotness 0likes Aaron Read all

preface The React.cloneElement method is encountered from time to time, and I read the official website documents many times, but I still have little knowledge of how to use it. Therefore, I go deep into the source code layer to find a calling solution. This article will analyze and summarize the usage of React.cloneElement from the source code layer version react source code version: 16.6.1 body usage Clone with element element as template and return new React element. You can modify props, key, ref through config parameter, and child element through children. Any parameter can be passed in React.cloneElement, and will be used as a child element of the new React element starting from the third parameter example import React from "react"; import "./style.css"; export default function App() { const Clone = React.cloneElement(<Temp/>, {key: 123, name: "Zhang San"}, <div>Hello, World 1.</div>, <div>Hello, World 2.</div>) return ( <div> {Clone} </div> ); } const Temp = (props) => { return ( <div> <span>Hello world, {props.name}</span> {props.children} </div> ) }; // Page output Hello world, Zhang San Hello, World.1 Hello, World.2 Parameter analysis element elements of react config object parameter, which can contain the following properties ref: not required to replace ref in the original element key: not required to replace key in the original element other attributes: all props as new element children The child element parameter is more appropriate here. Children parse declare that props, key, ref, self, source, owner are assigned default values based on element const props = Object.assign({}, element.props); // Reserved names are extracted let key = element.key;…

May 24, 2023 0comments 1345hotness 0likes Aaron Read all

Preface React Context is a commonly used state management mechanism provided by React to developers. Context can effectively transfer the same state in multi-level components, and can automatically notify each component to update when the status is updated. So how does React Context do this, and why does it need to be so designed? Why do you need Context in React's concept of data management, it has always followed the concept of individual data flow and data invariance. When we need to pass the state from the parent component to the child component, we often need to pass it explicitly through Props, for example: const Father:FC = () => { const [count, setCount] = useState<number>(0) return ( <Son count={count} /> ) } const Son:FC = (props) => { const { count } = props; return ( <span>{count}</span> ) } but what if the parent component needs to pass the state to the child component of the child component, that is, the descendant component? Or does the parent component need to be passed to multiple child components at the same time? Of course, continue to use props for layer-by-layer display transfer can certainly achieve this requirement, but that kind of code is too cumbersome and difficult to maintain, if you can maintain a global variable similar to that in Js in the parent component, wouldn't it be nice for all child components to use this global variable? Yes, that's what Context is for, but it's much more than that. What is Context? Context provides a way to pass data between component…

May 23, 2023 0comments 1331hotness 0likes Aaron Read all

Reading time is about 6 minutes. We improved the flexibility of React components in " yesterday. Learn more about React's & nbsp in the article "learn more about the wonderful use of forwardRef API " forwardRef & nbsp;API. When we need to manipulate a DOM node in a subcomponent, forwardRef & nbsp; meets our needs very well. But what if we want to manipulate some methods or properties in the subcomponent? you may immediately think of using a callback function to expose the methods or properties that need to be exposed in the child component to the parent component. For example, the following code: import React from 'react'; // Sub-component function ChildComponent(props) { const otherOperate = () => { // some code... } const handleClick = () => { if (props.onClick) { // callback function passed by the parent component props.onClick({ otherOperate }); } }; return ( <button onClick={handleClick}> Click me! </button> ); } // parent component function ParentComponent() { const handleClick = (propsFromChild) => { console.log('Button clicked!', propsFromChild); }; return ( <div> <ChildComponent onClick={handleClick} /> </div> ); } export default ParentComponent; in the above example, we pass the & nbsp; handleClick & nbsp; function as the & nbsp; onClick & nbsp; attribute to the & nbsp; ChildComponent & nbsp; subcomponent. When the button in & nbsp; ChildComponent & nbsp; is clicked, the handleClick & nbsp; function is called, exposing the & nbsp; otherOperate & nbsp; method in the child component to the parent component. In this way, when we click the button of the child component, the parent component…

May 22, 2023 0comments 1266hotness 0likes Aaron Read all

yesterday we discussed the useRef hook function in React: only this article, let you fully master the useRef hook function in React, one of the scenarios is to use useRef in the function component to create a ref object, and then bind it to an element to get a reference to that element in order to do various operations on the referenced element. What do we do when we want to access a reference to a child component in the parent component? The answer is achieved through React's forwardRef API. first acquaintance of forwardRef API forwardRef API allows us to pass a ref from the parent component to the child component, thus giving the parent component access to the DOM node or instance of the child component. The syntax is as follows: const SomeComponent = forwardRef(render); generally speaking, we can let the parent component access the child component through the callback function, that is, pass the callback function to the child component through props to access the DOM node or instance of the child component in the parent component. But in some cases, this approach is not convenient or flexible enough. forwardRef provides a more flexible way to solve this problem. when we wrap the subcomponents with forwardRef , we can access the subcomponents through the second parameter ref of forwardRef . The ref is then passed to the element or component that needs to be referenced in the child component so that the parent component can access the child component's instance or DOM node. This makes forwardRef a very…

May 20, 2023 0comments 1335hotness 0likes Aaron Read all