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 1256hotness 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 1629hotness 0likes Aaron Read all

these days we have shared some of React's built-in hook functions, such as useRef, useMemo, useReducer, useImperativeHandle, etc. These built-in hook functions provide great convenience for our development work. In addition to the built-in Hook provided by React, how do we write our own hook functions? Custom Hook allows us to share logic among multiple components, improving code reusability and maintainability. To customize a hook function, we should follow the following rules: Custom Hook must start with use . Custom Hook must be a function, and React's Hook can be used inside the function. Custom Hook must return data or methods. the above three rules must be followed, and they are also mentioned in the official React documentation. Let's use a simple counter example to demonstrate how to customize a general hook function. 1. Define the counter hook function to extract the general logic of a counter into a custom Hook, this hook function should have the following capabilities: can get the value of the current counter; can add value to the counter through the hook function; can reduce the value of the counter through the hook function. based on these three requirements, we can implement the following custom Hook: import { useState } from 'react'; // define the return value type of custom Hook type UseCounterReturnType = [count: number, increment: () => void, decrement: () => void]; // define a custom Hook export default function useCounter(initialCount: number = 0): UseCounterReturnType { // use useState to initialize count state and setCount function const [count, setCount] = useState(initialCount); // define the…

May 18, 2023 0comments 1216hotness 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 1371hotness 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