In fact, custom functions and create components with Hooks Hooks are very similar, with us usually written in JavaScript function almost exactly the same, may become more React Hooks
features, custom Hooks functions tend to function, and biased in favor of the component interface and business logic. Because little difference, so use is also very casual. If the project is small, but if the project is sufficiently complex, it makes the project structure is not clear enough. So learning Hooks custom function is still very necessary.
Write custom functions
In the actual development, in order to interface more attractive. Gets the size of the browser window is a frequently used functions, such frequently used functions can be encapsulated into a custom Hooks
function, remember the beginning must use use, in order to distinguish what is a component, what is the custom function.
Create a new file Example9.js
, and then write a useWinSize, we will use the time of writing useState
, useEffect
and useCallback
so the first use import
were introduced.
import React, { useState ,useEffect ,useCallback } from 'react';
Then write function, first with useState function setting size
state, and then write a modified state of each method onResize
, this method is used useCallback
, the purpose of caching method (useMemo to cache variables). Then when you first enter the method useEffect
to register resize
the listener time. In order to prevent the listener so when the method has been removed, using the return way to remove the monitor. Finally, it returns the size variable.
function useWinSize(){ const [ size , setSize] = useState({ width:document.documentElement.clientWidth, height:document.documentElement.clientHeight }) const onResize = useCallback(()=>{ setSize({ width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }) },[]) useEffect(()=>{ window.addEventListener('resize',onResize) return ()=>{ window.removeEventListener('resize',onResize) } },[]) return size; }
This is a custom function, and in fact, we used to write JS function makes no difference, so here not to do too much introduction.
Writing components and use a custom function
Custom Hooks
functions have been written, can be used directly, and the use JavaScript
of ordinary functions it is the same. Directly Example9
using components useWinSize
and display the results in real time on the page.
function Example9(){ const size = useWinSize() return ( <div>页面Size:{size.width}x{size.height}</div> ) } export default Example9
Then you can preview the results in a browser, you can see when we zoom in the browser window, the results will follow on the page changes. Description custom function played a role.
Transfer from: http: //www.jspang.com/posts/2019/08/12/react-hooks.html