React Hooks (Finished)

Introduction

Matt Choi
1 min readMay 31, 2021

In this post, we will talk about the last bit of hooks within React’s built-in hooks, which today will consist of useMemo, useCallback, and useLayoutEffect.

useMemo

This hook is used to help optimize your function by avoiding calculations on every render. useMemo returns a memoized value. Memoization just means a technique that is used to optimize and speed up your code. In order to use this hook, you will need to pass in a function and an array of dependencies, then useMemo will only run the memoized value when any of the dependencies changed.

const memoizedV = useMemo(() => someFunction(x, y), [x, y]);

useCallback

useCallback is useful for when you are passing down the same function in multiple components.

const displayCounter = () => {
return (
<p> {counter} </p>
)}
return (
<div>
<ChildComponent displayCount={displayCounter} />
</div>

If we use the hook useCallback then we will be able to prevent rerenders because they would all be using the same function object.

const displayCounter = useCallback(() => {
return (
<p> {counter} </p>
)}, [counter])
return (
<div>
<ChildComponent displayCount={displayCounter} />
</div>

useLayoutEffect

This hook is similar to the useEffect hook. This hook will run after rendering the component but before any updates have been made to the screen. This will run your entire code before anything on the UI is updated.

Conclusion

This wraps up all of the built-in hooks within React! In my free time, I will be coming back and updating each post with better code blocks/examples and add more info when I can!

--

--

No responses yet