Thy Shall Not Mingle Render With Declaration

Eli Goldstein
Aug 23, 2017 · 2 min read

If there were a “Ten Commandments” for React two of them would be

  1. Thy shall have a Render function in each component
  2. Thy shall keep said Render function….for rendering

In React, unless specified otherwise, our Render function is called every time our state is changed. The purpose of this is to keep our components up to data and dynamic relative to the information being passed into as their props.

However, there are bad and good ways to have your component render out information.

Lets look at the following example of a simple Dog Component with a onClick delete dog function.

In the above snippet, you can see that in my render function I am creating a arrow function that loops through my state, renders out each dog with an onClick function that points to our delete function we created above.

Now you may be wondering, what’s wrong with that?

The issue is how arrow functions work. Every time our component renders, it redeclares our arrow function because they aren’t saved anywhere for us to reference (that’s just how they work). Declaring and running a function that may or may not be called every time our page renders sounds like a bad idea, especially when optimization and loading speed is a priority.

So, what can we do to solve this?

Look at the correct code below

You may be wondering what is different with the above code.

Look at our render, we don’t have any arrow functions, instead, we are referencing a function that has already been declared.

In our case, in our render we are mapping over our states dogs and calling our component render function on them. This is turn gives each dog the onClick={delete} function. Then whenever a user clicks on a dog to delete it, our render just calls our ‘renderDogs’ function.

Isn’t that cleaner?

We are keeping our render function as simple as possible, and it’s only responsibility is to render, not declare functions.

Following this rule will keep your components, cleaner and faster

)

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade