Anatomy of a React Component — Render 📷
This is part one of a series on the Anatomy of a React Component, check out the other parts here!
The render method is arguably the most important part of any React component. It’s the only method that is required for every component. Without it, React would have no idea how to display a component.
What does it do?
As you can see in the example above, render often contains only a return with some JSX. This return tells React what you intend to display when you use this component. I like to think of render
as a Polaroid camera focused on a component; it knows how to frame the shot and where each element should be. However, it doesn’t do anything on its own.
How does it work?
Whenever React wants to show someone a component, it calls render
and gets back whatever the method returns. In terms of our camera metaphor, React clicks the shutter release and gets a photograph of what the component looks like right then.
When does it happen?
In general, React calls render
on a component whenever its props or state change. However, there are ways to limit how often a component re-renders, which will be discussed in the Lifecycle Methods chapter of this series.
Why do we need it?
React is a system for creating and displaying reusable pieces of the DOM. This is a fundamentally visual and dynamic process, and so we need a basic method that is equally visual and dynamic. render
is the perfect tool for this job. Its job is to take in dynamic data and generate a static output, the “photograph” of a given input.
Best practices
- Keep it simple - Complex logic should be refactored into class methods or separate components
- Keep it pure - Don’t manipulate state or the DOM, steer clear of side-effects, and always render the same output given the same inputs
- Keep it lean - A single component shouldn’t render too much. If your component is creating lots of individual elements, it could likely be split into multiple components
That’s the render method! It’s a relatively simple idea, but without it React would be impossible. Check out the main article for info on other pieces that make React tick, and follow me to hear about more articles like this.
Be sure to leave a comment and tell me what you thought!