DEV Community 👩‍💻👨‍💻

Cover image for You (most likely) don't need to optimize React
Ivan Levenhagen for Woovi

Posted on

You (most likely) don't need to optimize React

One of the biggest pitfalls in software development is early optimization, we always want our code to run as fast as possible and try to squeeze every single drop out of it. But going through this process too early can do more harm than good.

Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

The most common mistake in React projects is the use of the useCallback and useMemo hooks, you (most likely) don't need to use these hooks, let's take a look how useMemo works to understand why.

So, what does useMemo do? It accepts two parameters, a Callback and an array of dependencies, and returns the return of this callback. The dependency array is used so useMemo can track if this value is stale, if the dependencies values changes, this mean we have to calculate the value again.

Now, all of this sounds amazing, so why don't we just useMemo everywhere? Let's take at this very contrived example:

const fruits = ['apple, 'banana', 'orange']
const initialFruit = useMemo(() => fruits.find(item => item === 'orange'), [])
const [fruit, setFruit] = useState(initialFruit)
Enter fullscreen mode Exit fullscreen mode

While it's great that we're not running the .find on every render, we have to ask ourselves, is it worth it? useMemo itself is more code it isn't completely free to use, we added more complexity to our code which makes it harder to maintain. React is fast, you don't need to optimize every single thing, what's expensive in React is committing changes to the DOM not a simple calculation.

So when should I optimize React? It's actually very easy to know. If you're asking yourself this question, you don't need it. When the time comes that performance is a problem on your code, you'll know it.

Focus your time creating new features for your application, not optimizing code that you probably don't even need to.

If you want to work with us, we are hiring!

Top comments (0)

DEV has this feature:


Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠