Understanding the useMemo design
React provides a useMemo
hook to support a value assignment through a function that can either return a new value or an old value from the previous update:
const Title = () => { const label = useMemo(() => { return "Hello World" }, []) }
The useMemo
function takes a create
function as its first input argument. This function returns a new value if invoked. The second parameter is a deps
dependency array, similar to deps
in useEffect
. In the preceding case, "Hello World"
is assigned to a label
variable only once after the mount.
There's no additional data structure required for useMemo
other than the basic hook support, as shown in Figure 6.1:
The hook's state persists between updates, and it's up to each hook function to define what (or in which format) it wants to persist. For instance...