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