-
Book Overview & Buying
-
Table Of Contents
Designing React Hooks the Right Way
By :
React provides a useRef hook to create a ref:
const Title = () => {
const ref = useRef(null)
return <h1 ref={ref}>Hello World</h1>
}
The useRef hook takes an initial value as its only input argument and returns a ref object, putting that initial value under the current property.
There's no additional data structure required for useRef, other than the basic fiber hook support:
Figure 8.2 – useRef design
Just like useState and useEffect uses state to store state and the effect, useRef uses state to store the ref. Next, let's take a look at how it's implemented.
The useRef hook follows a typical hook setup where it takes a path of either mountRef or updateRef, depending on whether the fiber is under mount or update via the isFiberMounting flag, as explained in Chapter 3, Hooking into React:
function useRef(initialValue) {
if (isFiberMounting) {...
Change the font size
Change margin width
Change background colour