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 1217hotness 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

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 1236hotness 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

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
12345…6