Today we are going to learn the common design pattern of JavaScript-- the strategy pattern definition defines a series of algorithms, encapsulating them individually, and making them interchangeable. extract and encapsulate seemingly unrelated code to make it easier to understand and expand. Let's understand it through an example: Application scenario there are different strategies to accomplish several things. For example, performance calculation, form validation rules calculate the year-end bonus after performance appraisal. S performance is four months' salary, A performance is three months' salary, B performance is two months' salary before use define a function to calculate bonus calculateBonus . The input parameters of the function are performance level and monthly salary function calculateBonus(level, salary) { switch (level) { case "s": { return salary * 4; } case "a": { return salary * 3; } case "b": { return salary * 2; } default: { return 0; } } }; calculate bonus calculateBonus('s', 10000); // 40000 calculateBonus('a', 5000); // 15000 if we want to modify the performance rules, we need to change the logic in the calculateBonus function, which violates the open and closed principle, so we can consider using the policy mode at this time. improve decouple all the logic function getS(salary){ return salary * 4 } function getA(salary){ return salary * 3 } function getB(salary){ return salary * 2 } function calculateBonus(level, salary) { switch (level) { case "s": { return getS(salary); } case "a": { return getA(salary); } case "b": { return getB(salary);; } default: { return 0; } } }; this is still a lot of…

June 13, 2023 0comments 1210hotness 0likes Aaron Read all

Today we will learn about the design pattern commonly used in JavaScript-- singleton pattern definition ensures that there is only one instance of a class and provides a global access point to it means that it is unique and can be accessed globally singletons correspond to multiple cases. Generally, we create a class that can instantiate many objects, which is multiple cases, while singleton patterns can instantiate only one object. This instance object can be cached and reused. Application scenario when you encounter something in development, it feels like it has been reused many times. If you can cache this object and use this instance object each time, instead of recreating one object, you can use singleton mode here. for example, in front-end page development, our login pop-up window is generally unique, no matter how many clicks, only one login pop-up window will be created. And the pop-up window should be cached, where the rendering efficiency of the page can be improved, so the login pop-up window can be created in singleton mode. before use We are going to create a login pop-up window // Business logic: create a login pop-up window function createLoginLayer(){ // create a login pop-up box const div = document.createElement("div"); div.innerHTML = Login pop-up window; // set the pop-up window style to invisible div.style.display = "none"; // add a box to the page document.body.appendChild(div); // return to this login pop-up box return div; }; then bind the click event to the login button, click on it, create a pop-up window, and display it on the page.…

June 9, 2023 0comments 2021hotness 0likes Aaron Read all

Today, let's start to learn the common design patterns of JavaScript. In fact, design patterns, like algorithms, are universal and empirical ideas that deviate from the language. Front-end programmers are also software engineers, who need a solid professional foundation, and design pattern is also one of the important professional foundations of computer. what is a design pattern Design patterns are concise and elegant solutions to specific problems in the process of software design when developing business code, you are faced with a variety of different needs, and different situations will sum up different solutions. We can sum up these experiences , and make rational use of to different problems, so that we can use common solutions to solve problems . To keep it simple, design patterns can be understood as tricks and tricks when writing code. Design patterns have SOLID five design principles single function principle ( S ingle Responsibility Principle): a program only does one thing well Open and closed principle ( O pened Closed Principle): open to expansion, closed to modification Internal substitution principle ( L iskov Substitution Principle): subclasses can override the parent class and appear where the parent class appears Interface isolation principle ( I nterface Segregation Principle): keep the interface single and independent dependency inversion principle ( D ependency Inversion Principle): use methods to focus only on interfaces and not on the implementation of specific classes Front-end development uses JavaScript. We should focus on the first two principles, namely, single function principle and Open and closed principle Why do you need a design pattern Why…

June 8, 2023 0comments 1279hotness 0likes Aaron Read all

We know that useMemo and useCallback are mainly used to cache intermediate states and reduce meaningless render to improve performance. But recently I have found that I have been misunderstanding their use! misunderstanding of useMemo Please take a look at the following code. Even with useMemo , the second subcomponent is re-rendered without the change of isZero ! import { useCallback, useMemo, useState } from "react"; const Child = ({ value, onClick }) => { return ( <div style={{ height: 100, background: `#${(~~(Math.random() * (1 << 24))).toString(16)}` }} > my value is {value.toString()} </div> ); }; export default function App() { const [count, setCount] = useState(0); const isZero = useMemo(() => !!(count % 3), [count]); const onClick = useCallback(() => setCount(count + 1), [count]); return ( <div className="App"> <button onClick={onClick}>click me</button> <Child value={count} /> <Child value={isZero} /> </div> ); } 💡 related reading in fact, the reason has also been mentioned in previous articles: React every time the state of a component changes, it starts from the current component until all leaf node components are re-rendered. The article also mentions the solution to this problem: the subcomponent is wrapped with the memo function, and the component can render as expected. however, at this point we remove useMemo , and the subcomponents are still rendered as expected. memo is similar to useMemo , which is based on a shallow comparison of Object.is and is only valid for non-reference types. so in the above example, it makes no sense to use useMemo . misunderstanding of useCallback however, in the above example, the…

June 6, 2023 0comments 1266hotness 0likes Aaron Read all

Please think about a question: if there is a HTML tag, and React has two hook around it, then this tag must be very important for the future development of React . Is that all right? The tag is-- form . React around form , there are two new hook : useOptimistic useFormStatus this article will talk about the layout and development of React around form . the development of Next.js speaking of the future development of React , we must start with Next.js . After all, React team members either join the Next team or are on their way. web the parts of development that involve front-end interaction mainly include: render the front-end page based on the back-end data Save data to the backend according to the input of the front-end user The development of Next.js mainly focuses on the above two points. render the front-end page based on the back-end data in the earlier stage, the main features of Next.js are SSR , SSG . That is, the process of rendering the front-end page based on the back-end data is moved from the front-end to the back-end. the Next.js route for this period is called Pages Router . time comes to Next.js v13 . App Router with RSC (React Server Component) as the core replaces Pages Router as the default configuration. many friends are not familiar with RSC and regard it as an experimental feature. In fact, RSC has landed via Next.js . one sentence understanding RSC -client components ( React components rendered in the browser) can be…

June 5, 2023 0comments 1178hotness 0likes Aaron Read all

Preface this article shows you how to use React and DOM things to achieve a compelling interactive hover box effect. By hovering over the mouse, the box will randomly change the color and display shadows, adding dynamic and visual appeal to the page. Read this article and you'll learn how to use React to implement event handling and dynamic styling, bringing more interesting interactions to your Web application. scene in modern Web applications, interactivity and dynamic effects are critical to improving the user experience. Hovering effect is a common way of user interaction, when the user hovers the mouse over a specific area, the relevant elements will change to attract the user's attention. In this article, we will explore how to use React to implement a CSS special effect of a hover square effect. Let's take a look at → Development first, import React and some necessary hook functions, as well as the stylesheet we will use in the component. As follows: import React, { useEffect, useRef, useState } from 'react'; import './index.less' The code for the index.less file is as follows: .App { background-color: #111; display: flex; align-items: center; justify-content: center; overflow: hidden; margin: 0; } .container { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; max-width: 600px; overflow: hidden; } .square { background-color: #333; box-shadow: 0 0 2px #000; height: 16px; width: 16px; margin: 2px; transition: 2s ease; } .square:hover { transition-duration: 0s; } then defines an array of colors and a constant SQUARES to set the number of squares. As follows: const colors = ['#861104', '#7611a0', '#127ec7',…

June 1, 2023 0comments 1291hotness 0likes Aaron Read all

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
1…34567…12