1. Usage of useRef
- Syntax: const refObj = useRef(initialVal), where refObj={current: initialVal}
- refObj is mutable
- Value persists through the react lifetime (even after you changed the initialVal)
- Use cases
- Managing DOM directly, e.g.: textfield focus, integrate with 3rd party DOM libraries
- <input ref={textInput} type="text" />, where const textInput = useRef(null) is declared on top of the functional component, by accessing textInput, you retrieve the input DOM element for further processing
- Store instance variables
- Use to store setInterval or setTimeout's ID for clearing at unmount stage.
- const intervalRef = useRef(null);
- intervalRef.current = setInterval(() => { // something... });
- clear stuffs in return function of useEffect return () => { clearInterval(intervalRef) }
- Use as render counter when you want to know how many re-render made by React (since ref values keep throughout the React lifetime)
3. Usage of useCallback
References
4. About useEffect and rendering timing
useEffect always run after the UI rendering is done, the useEffect will check the dependecy array against the value of the last render, and run the useEffect callback when they are different from each other.
References
沒有留言:
張貼留言