前言
还有即将在国外投身秋招的小伙伴吗?本文是将在写大项目过程中用到的React useEffect useRef实践心得翻译成英文的笔记,给将要在国外面试和在国内想学习英文的小伙伴们都做个参考~
useEffect
-
useEffect((setup) => {...; return (cleanup) => {}}, [dependencies])-
Cause a side effect (run the
setupfunction) every time thedependencieschange. -
dependenciesare values that, whenever they change, the useEffect hook is going to run- Note, sometimes even when the page re-renders, the
dependencydoesn't change! e.g. When your current tab name is being tracked by useState, anddependencyis the tab name you are currently on. You click the same tab multiple times. Even though the useState hook gets called whenever you click on tab and page re-renders, tab name doesn't change, souseEffectdoesn't run.
- Note, sometimes even when the page re-renders, the
-
If you leave
dependenciesempty, you are only running useEffect On Mount
-
-
You can use the
setupfunction to add an event listener, and record the event result in a useState -
useEffect can return a
cleanupfunction that will be called when the component unmounts. This can help you remove event listeners and prevent them from adding up.- When dependencies change, the
cleanupfunction runs first, then thesetupfunction runs
- When dependencies change, the
useRef
-
A Ref is similar to State in that it persits inbetween renders, but a Ref does not cause a component to re-render when the Ref gets changed
-
Refs are seperate from a component's render cycle
-
UseRef help you avoid infinite loops when using states: In useEffect if you do not leave the dependencies empty, then if you call a setState function, it updates the state, causes component to re-render, the re-render triggers the useEffect again, repeat and you get infinite loops.
-
const refCount = useRef(0)- Returns an object with a current property:
refCount = {current : 0} - Always remember to use refCount.current to access its value!
- Returns an object with a current property:
-
Then in useEffect you can write
refCount.current += 1, and you don't need to worry about infinite loops -
useRef can also help you to keep track of the previous value of a state. When you store the prev value of a state inside a ref, every time a ref changes it will not cause a re-render, so you save 1 extra render that you don't need compared to using another state.
Reference
总结
useEffect是React同useState一样最常用的钩子,基本上fetch任何API都需要用到它。然而因为每次state change都会触发re-render,如果dependencies没写好就会出现无限循环。这时候就需要知道react还有useRef这个钩子,清楚Ref和State之间的区别,才能把useRef和useState结合起来用避免无限循环。希望大家看完此笔记能够避免错误~