Photo by Freysteinn G. Jonsson on Unsplash

Hooks are a new addition in React 16.8.

They let you“ hook into” use state and other lifecycle features without writing a class.

With class components, we tie updates to specific lifecycle events.

In a function component, we instead use the useEffect hook to run code during the major lifecycle events.

Let’s look at an example to see what the difference is.

Imagine you have a computationally expensive function that returns a filtered dataset based on a specified dateRange. Because the function takes some time to run, we will store it in a state object and only update it when dataRange changes.

It is much cleaner to write it with React Hooks and think about what values stay in-sync.

We are storing data in state to prevent re-calculating it every time our component updates.

useMemo()

But we no longer need to use state in function component! Here to the rescue is useMemo(), which will only re-calculate data when its dependency array changes.

We can also just define variables right inside of our function.

This works fine, unless the getDataWithinRange() function is computationally expensive.

useMemo() is good to use to keep things speedy especially when handling large datasets.

As seen in the examples React Hooks is shorter, cleaner and easier to read.

For more information read here: https://reactjs.org/docs/hooks-overview.html

I like to do crazy things with CSS & JavaScript. My brain occasionally runs out of memory so I need to write down my thoughts.