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

React Hooks is a new feature introduced by React version 16.8 that allows us to use state and other React features without writing class components. Among them, useState and useEffect are the most commonly used. When using React Hooks, because there are no instances of function components, Hooks relies on closures to access and update state. However, when using Hooks, we need to pay attention to the closure trap problem. what is a closure trap? A closure means that a function can access variables defined outside the function. In React, Hooks functions are also closures, and they can access variables defined outside the function. The closure traps of React Hooks are similar to those of ordinary JavaScript, but because of the design of React Hooks, you may encounter some specific problems when using Hooks. Closure traps in React Hooks mainly occur in two situations: use closures in useState; uses closures in useEffect. closure traps in useState closures are used in useState mainly because the parameters of useState are executed only once when the component is mounted. If we use closures in useState, the values of variables in closures are cached, which means that when we update the state in the component, the values of variables in closures are not updated. in the handleClick function, the setCount function returned by useState is used to update the count status value. Because setCount is defined in the App function, and the handleClick function can access the variables and functions defined in the App function, the handleClick function forms a closure that can access…

May 10, 2023 0comments 1469hotness 0likes Aaron Read all

Let's start with some nonsense useUpdateEffect & nbsp; usage is equivalent to & nbsp; useEffect , but ignores execution for the first time, only if it depends on updates. there are scenarios in which we do not want to perform effect when rendering for the first time, such as when searching, the search method is called only when the keyword changes. This hooks is also used more often in daily work, so it is necessary for us to write its source code, 🤓. Let's see the effect for the first time, only useEffect prints count, and only when count changes, useUpdateEffect prints count Source code implementation import React, { useEffect, useRef } from 'react'; const useUpdateEffect = ( effect: React.EffectCallback, deps: React.DependencyList, ) => { let isFirst = useRef(true); useEffect(() => { if (isFirst.current) { isFirst.current = false; return; } return effect(); }, [deps]); }; complete demo source code import React, { useEffect, useRef } from 'react'; import { Button } from 'antd'; const useUpdateEffect = ( effect: React.EffectCallback, deps: React.DependencyList, ) => { let isFirst = useRef(true); useEffect(() => { if (isFirst.current) { isFirst.current = false; return; } return effect(); }, [deps]); }; const Demo = () => { const [count, setCount] = React.useState(0); useEffect(() => { console.log('count' of useEffect, count); }, [count]); useUpdateEffect(() => { console.log('count' of useUpdateEffect, count); }, [count]); return ( <> <div>Count: {count}</div> <Button type="primary" onClick={() => setCount(count + 1)}> Click me + 1 </Button> </> ); }; export default Demo; reference interested friends can look at the source code of react-use and ahooks to…

May 9, 2023 0comments 1370hotness 0likes Aaron Read all

Hello, everyone. I'm Carson. The code volume of React can be said to be quite large. Is there a function in such a large library that is not mentioned in the document but actually exists ? the answer is yes. this article will introduce you to hidden egg features that are not mentioned in three documents. ref cleanup in the current React , Ref has two data structures: <T>(instance: T) => void {current: T} for most requirements, we will use the second data structure. It is also the data structure returned by useRef and createRef . the first data structure is mainly used for DOM monitoring. For example, in the following example, the size of div is reflected in the height state: function MeasureExample() { const [height, setHeight] = useState(0); const measuredRef = useCallback(node => { if (node !== null) { setHeight(node.getBoundingClientRect().height); } }, []); return ( <div ref={measuredRef}>Hello Kasong</div> ); } but in the above example, the size change of DOM cannot be reflected in real time to the height state. To reflect real-time changes, you need to use native API that monitors DOM , such as ResizeObserver , monitor DOM size change IntersectionObserver , monitor DOM visual area changes MutationObserver , monitor DOM tree changes these API are usually event-driven, which involves unbinding events when monitoring is not needed. since event binding occurs in the ref callback, naturally, unbinding events should also occur in the ref callback. For example, modify the above example with ResizeObserver : function MeasureExample() { const [entry, setEntry] = useState(); const measuredRef = useCallback((node)…

May 5, 2023 0comments 1344hotness 0likes Aaron Read all

this article is used to record some of the author's gains in the section strict mode in the official React18 documentation, concerning the role of strict mode, why React executes useEffect twice, and how to optimize it. strict mode (Strict Mode) what is strict mode strict mode is a tool to check for possible problems in your application. Strict mode only runs in a development environment, but it has no impact in a production environment. import React from 'react'; function ExampleApplication() { return ( <div> <Header /> <React.StrictMode> <div> <ComponentOne /> <ComponentTwo /> </div> </React.StrictMode> <Footer /> </div> ); } you can use React.StrictMode to wrap the apps you want to check. Apps without packages will not be affected. For example, the & lt;Header / & gt; component in the above code will not be affected by the strict mode, only the & lt;ComponentOne / & gt; and & lt;ComponentTwo> that we package will be affected by the strict mode. the role of strict mode strict mode makes the following checks identify unsafe lifecycles, such as componentWillMount. Later, it was upgraded to componentDidMount check on ref, a previous version of API, I hope you can replace it with a new version warning of findDOMNode being deprecated detect unexpected side effects found API with expired context ensure reusable state ReactThe official document of React provides an example, which should mean that if we jump from Route A to Route B and then return from Route B. ReactI hope to immediately display the original state, so that I can cache the state…

April 20, 2023 0comments 1623hotness 0likes Aaron Read all