Hello, everyone. I'm Carson. the following React component code uses three use keywords. Do you understand their role? 'use client' function App() { using data = use(ctx); // ... } it is true that I haven't written React for several days, and I can't even understand the grammar. This article will talk about the respective meanings of these use keywords. use client begins with the 'use client' declaration at the top of the code, which is used in a manner similar to the strict mode declaration: 'use strict'; // here is the JavaScript code in strict mode The 'use client' declaration is defined in the RSC ( React Server Component , server-side component) protocol. the React application of RSC is enabled. All components are rendered on the server by default (you can experience it through Next v13 ). Only component files that declare 'use client' are rendered at the front end. suppose our React application component structure is as follows, where red represents server component , blue represents client component (declare 'use client' ): then when the application is packaged, the D and E components will be packaged into separate files. On the front end, React can render A, B, C components directly. But for D and E, you need to request back the component code in the form of JSONP before rendering. using keyword then comes the using keyword before the data variable: using data = use(ctx); The using keyword is proposed by tc39 proposal ECMAScript Explicit Resource Management , and is used to provide unified lifecycle management (when…

June 30, 2023 0comments 1216hotness 0likes Aaron Read all

May 30th is the 10th anniversary of React . I pulled React the latest code, and it doesn't matter. There are already 22 hook . where: react package exports 21 react-dom package exports 1 ( useFormStatus ) this article will talk about the role of React from the perspective of the development of hook over the years. the change of times up to now, the development of React has mainly gone through three periods: CSR period (client rendering period) concurrent period RSC period (server component period) the current 22 hook are also the products of these three periods. CSR period back in 2013, in order to solve the increasingly complex interactions of facebook , jordwalke developed React . After a period of exploration, React gradually formed a set of development mode that satisfies CSR . this development model migrates from ClassComponent to FunctionComponent , resulting in the first batch of hook . These hook are all related to the development mode of CSR . For example: related to the flow of states: useState useReducer useContext related to side effects of treatment: useEffect useLayoutEffect related to improving the degree of freedom of operation: useRef related to performance optimization: useMemo useCallback related to debugging: useDebugValue with the continuous iteration of React , several hook are introduced. In essence, they all aim to improve the development model of CSR and supplement or restrict the existing hook capabilities: useImperativeHandle (control useRef to prevent it from getting out of control) useEffectEvent (a supplement to useEffect capabilities) useInsertionEffect (supplement to useEffect scenarios) useMemoCache (reduce the mental…

June 30, 2023 0comments 1369hotness 0likes Aaron Read all

1 useUpdate how do I force a component to refresh in a react function component? Although react does not provide a native method, we know that when the state value changes, the react function component will be refreshed, so useUpdate takes advantage of this. The source code is as follows: import { useCallback, useState } from 'react'; const useUpdate = () => { const [, setState] = useState({}); return useCallback(() => setState({}), []); }; export default useUpdate; you can see the return value function of useUpdate, which calls setState with a new object each time, triggering the update of the component. 2 useMount although the react function component does not have the life cycle of mount, we still have this requirement, that is, the requirement of executing once after the component is rendered for the first time can be encapsulated by useEffect. If you only need to set the dependency to an empty array, then you can only perform a callback after the rendering is completed: import { useEffect } from 'react'; const useMount = (fn: () => void) => { useEffect(() => { fn?.(); }, []); }; export default useMount; 3 useLatest react function component is an interruptible, repeatable function, so every time there is a change in state or props, the function will be re-executed. We know that the scope of the function is fixed when the function is created. If the internal function is not updated, then the external variables obtained by these functions will not change. For example: import React, { useState, useEffect } from 'react';…

June 26, 2023 0comments 1255hotness 0likes Aaron Read all

Preface package.json is an important file for describing and configuring a project, which contains a number of fields and options that can affect project construction, dependency management, script execution, and so on. Understanding these fields can help developers better understand and control the behavior of the project. package.json for most front-end developers, knowing dependencies and devDependencies is enough. However, for library developers or developers with more advanced needs, it is necessary to understand the other fields of package.json. the fields introduced in this article are divided into official fields and unofficial fields. Unofficial fields are supported by mainstream packaging tools (webpack,Rollup) and are designed to provide more advanced configuration and functionality to meet specific build needs and may not be universal. current version: v7.24.2 I. required attribute 1. name defines the name of the project, not with "." Start with "_" and cannot contain uppercase letters 2. version defines the version number of the project in the format of large version number. The second edition number. Revision number II. Description information 1. description Project description 2. keywords Project keywords 3. author Project author "author": "name (http://barnyrubble.tumblr.com/)" 4. contributors Project contributor "contributors": [ "name <[email protected]> (http://barnyrubble.tumblr.com/)" ] 5. homepage Project home page address 6. repository Project Code Warehouse address 7. bugs address of project submission question // address for submitting questions and email address for feedback. Url is usually the issues page in Github. "bugs": { "url" : "https://github.com/facebook/react/issues", "email" : "[email protected]" } 8. funding specify the financial support method and link for the project "funding": { "type": "patreon", "url": "https://www.patreon.com/my-module"…

June 20, 2023 0comments 1353hotness 0likes Aaron Read all

what is useEffect? official explanation: useEffect is a React Hook that allows you to synchronize components with external systems. What does mean? Personal understanding is that it can be executed at different times according to different dependent values or return values. Let's talk about the first usage first 1: trigger update in useEffect example 1: when we do something automatically in the process of component creation, we can do this in functional components error example import { useEffect } from 'react' function App () { const [ count , setCount] = useState(0) useEffect(()=> { initData() }) const initData = () => { setCount(count + 1) } return ( <div> {count} </div> ) } what problems will you find if you use useEffect like this? when our component finishes rendering to execute useEffect, call the initData function to trigger the update through the setCount setting value. Once the update useEffect is executed at the end of the rendering, it becomes endless loop . so you should write this, passing in the empty array of the second parameter useEffect, which means that the component is only executed once in the rendering process correct example import { useEffect } from 'react' function App () { const [ count , setCount] = useState(0) useEffect(()=> { initData() }, []) const initData = () => { setCount(count + 1) } return ( <div> {count} </div> ) } 2: repeated useEffect in usage 2 example 2: what will it do if you write multiple useEffect in the process of component rendering? import { useEffect, useState } from…

June 17, 2023 0comments 1235hotness 0likes Aaron Read all

Today, I will introduce several React hooks , which are not commonly used, but are very useful. useSyncExternalStore listen for external data changes external data sources need to provide a subscription function, and this function needs to return the method of unsubscribing import React from 'react'; import { store } from './store.js' export const App () { const data = useSyncExternalStore(store.subscribe, store.getData) return <> <button onClick={store.add}>add+</button> {data} </> } // store.js let conut = 0; let listeners = []; export const store = { add () { count ++; }, subscribe(listener) { listeners = [...listeners, listener]; return () => { listeners = listeners.filter(l => l !== listener); }; }, geetDate () { return count; } } useId generate globally unique ID, give up Math.random () bar import { useId } from 'react'; function App() { const uuid = useId(); return ( <>{uuid}</> ); } useLayoutEffect trigger before layout update import { useState, useRef, useLayoutEffect } from 'react'; function Tooltip() { const ref = useRef(null); const [tooltipHeight, setTooltipHeight] = useState(0); useLayoutEffect(() => { const { height } = ref.current.getBoundingClientRect(); setTooltipHeight(height); }, []); return <></> } useDeferredValue UI defer updates without handwritten anti-shake function import SearchResults from './SearchResults.js'; export default function App() { const [query, setQuery] = useState(''); const deferredQuery = useDeferredValue(query); return ( <> <label> Search albums: <input value={query} onChange={e => setQuery(e.target.value)} /> </label> <Suspense fallback={<h2>Loading...</h2>}> <SearchResults query={deferredQuery} /> </Suspense> </> ); } useReducer customize a lightweight redux const initialState = {count: 0}; function reducer(state, action) { switch (action.type) { case 'increment': return {count: state.count + 1}; case 'decrement': return {count:…

June 16, 2023 0comments 1628hotness 0likes Aaron Read all

Today we will learn the design pattern commonly used in JavaScript-- proxy pattern In real life, an agent generally means that handles transactions on behalf of the authorized party . In law, it refers to the expression of intention of the agent, the authorized party, to act legally with a third party in his own name. A legal act committed as a result of authorization may have legal effect directly on the authorized party. that is, when it is not convenient for the customer to access an object directly, a proxy object can be provided for the customer to access. After a series of processing to the request, the proxy object transfers the request to the ontology object. definition provides a substitute or placeholder for each object to control access to it. The stand-in object can process the request in advance and then decide whether to transfer it to the ontology object. there are also many proxy modes, such as protection agents and virtual agents. Protection Agent is used to control access to target objects with different permissions; Virtual Agent refers to delaying the creation of expensive objects until they are really needed. Application scenario when we access an object directly, or when we are dissatisfied with our needs, we can consider using a stand-in object to control the access to that object. Let's look at the virtual proxy mode with an example of image preloading: before use first use a loaded picture to occupy space, then load the picture asynchronously, and then fill it into the img node when…

June 15, 2023 0comments 1261hotness 0likes Aaron Read all

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 1209hotness 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
12