You Wish You Had Known This Quirk Sooner
I started working with React about 6 years ago and started advocating its superiority in terms of Developer Experience (DX) ever since. However, an important thing to consider is that React is by no means a one size fits all solution and if you’ve tried to build a simple static website with React, you might have realized you’ve complicated yourself into unnecessarily convoluted concepts. But if you’ve decided React is the right fit for your next project, you might as well leverage the power of React to its full stretch.
For that exact purpose, a deeper understanding of one of the core principles behind React’s performance superiority — the virtual DOM, is recommended. Knowing the internals is probably not necessary to build React apps but by understanding the underlying concepts, you should be able to write better, more robust React apps.
ReactJS uses a heuristic algorithm that computes changes in the DOM structure using a diffing mechanism that computes changes using an in-memory version of the DOM. By leveraging this, React can update only parts of the page that have changed instead of re-rendering the entire page. React authors call it reconciliation.
Notice the word heuristic? That changes everything about what most people assume about the virtual DOM, rendering performance & worst of all — incorrect data in the view (Yes, that can happen!). React uses certain assumptions while diffing for changes and if you aren’t cautious, the algorithm might appear like it went belly-up.
It is a pretty common practice while iterating over lists to use the index as the key. But in most cases, using an array index as your key can be considered an anti-pattern. Here’s why —
Common practices are not always ideal practices
Each child in an array should have a unique "key" prop.
To get rid of this warning, it is pretty common to pass the index of the array to the elements returned from array iterations. Did you know it can potentially cause an incorrect application state? As safe as it might seem, this practice can be very bad in certain common use-cases. For example, let’s consider a list of inputs that are rendered using React:
{
list.map((item, i) => (
<div>
<label>item.name</label>
<input key={i} />
</div>
);
}
This piece of code displays a list of inputs. It works fine as long as the list is unaltered (no reordering, splicing, or filtering). Guess what happens when you prepend an item to the list? You will see a new text input is rendered, but the values inside the inputs are not re-rendered!
I ran into this weird behavior a while ago when I was trying to do render a list of uncontrolled inputs. Back then, I didn’t even know using the index as a key is not a recommended approach so I figured I’d just use controlled inputs. It technically worked but there is a performance trade-off.
The issue would have been easily solved by using the id
of the item being rendered or any other identifier that is unique within the list. Here’s how it looks when the key used is the id
instead of the index
Back in the early 1900s, Serbian astrophysicist Milutin Milankovitch decided to work on a puzzle that no one else had successfully solved: linking the physics that governed the Solar System with the theory of Earth’s climate. As the Earth orbits the Sun, you’ll barely notice any year-to-year changes, as they’re relatively minuscule. Sure, the phases of the Moon shift, the exact date and time of equinoxes and solstices vary, and timekeeping requires the regular insertion of leap days to keep the seasons aligned with our calendar.
While Newton’s law of gravitation and Kepler’s laws of planetary motion are relatively simple, however, anything more complex than the simplest system imaginable can lead to incredibly elaborate orbital complications. In the case of the Earth, it’s affected by:
- the fact that it rotates on its axis,
- it moves in an ellipse, rather than a circle, around the Sun,
- it has a large, natural satellite: the Moon,
- which in turn orbits the Earth tidally locked, inclined at an angle to Earth’s orbit and axial rotation, and in a quite eccentric ellipse,
- and the small (but not completely negligible) gravitational influence of the other bodies in our Solar System.
All of these effects interplay with one another to determine the long-term evolution of Earth’s orbit.
When the Earth’s north pole is maximally tilted away from the Sun, it’s maximally tilted towards the full Moon, on the opposite side of the Earth, while when your hemisphere of the Earth is maximally tilted towards the Sun, it’s maximally tilted away from the full Moon. The Moon stabilizes our orbit but also slows the Earth’s rotation, with both the Moon and Sun as well as the other planets all playing roles in the long-term evolution of Earth’s rotation, axial tilt, and orbital parameters. (NATIONAL ASTRONOMICAL OBSERVATORY ROZHEN)
There are a few important rules at play. One is the law of gravitation, and the fact that these aren’t point-like objects we’re talking about, but rather spheroids: physical objects of a real, finite size and with intrinsic angular momentum to them. That angular momentum, for each object in our Solar System — and particularly for the Earth, Moon, and Sun — is split up into the spin of each body, or its rotational motion, and its orbital angular momentum, or its revolutionary motion. (Yes, even the Sun doesn’t remain stationary, but rather makes its own “wobbly” motion due to the gravitational influence of the other bodies in the Solar System.)
What Milankovitch found, perhaps surprisingly to some, is that these effects all add up to cause three major long-term variations, arising from the interactions of these Solar System bodies.
- Precession, or the fact that the direction that Earth’s axis points rotates over time.
- Axial tilt, which changes ever so slightly from its current 23.5° over time.
- Eccentricity, or how circular vs. elliptical Earth’s orbit is.
Although there are other effects, they’re all minor compared to these three major ones. Let’s look at them individually.
Earth’s rotational axis will precess over time due to two combined effects: axial precession (shown here) and apsidal precession, as its elliptical orbit also precesses. The combined effects, which have ~26,000 and ~112,000 year periods, respectively, result in a total precessional period of closer to ~23,000 years. (NASA/JPL-CALTECH)
1.) Precession. This one is actually pretty straightforward: the Earth spins on its axis, which is inclined at 23.5° with respect to our revolutionary path around the Sun. When our axis is pointed perfectly perpendicular to the line connecting the Earth to the Sun, we experience equinoxes; when the axis is pointed along the Earth-Sun line, we experience solstices. Although the timing of both equinoxes and solstices would change over time, astronomically, the insertion of leap days keeps the equinoxes centered around March 21 and September 23, with the solstices occurring around December 21 and June 21.
But the physical direction that our axis point does, in fact, change over time. Right now Polaris is our “north star” because our axis points towards it to within 1°, which is remarkable but unusual for a bright star. Over long periods time, the direction that Earth’s rotational axis points will make a complete circle, as two effects both come into play:
- our axial precession, which is Earth’s “wobble” relative to the stars, largely due to the Moon and Sun,
- and our apsidal precession, which is how Earth’s ellipse “wobbles” as we orbit the Sun, primarily due to Jupiter’s and Saturn’s influences.
Today, in the year 2020, Polaris lies extremely close to the exact north celestial Pole. The red circle traces out the direction that Earth’s axis will point along over time, indicating which star will best serve as a pole star in both the far future and the distant past. Vega, the brightest star in this vicinity, will be our pole star in a little over 13000 years. (WIKIMEDIA COMMONS USER TAUʻOLUNGA)
Axial precession causes Earth to make a full 360° turn on its axis every 25,771 years, while the apsidal precession leads to an additional 360° turn (in the same direction) every ~112,000 years or so. For an observer on Earth, if we could live that long, we’d see the pole stars change in a periodic fashion every 23,000 years or so, as these effects combine in an additive fashion. Thousands of years ago, the star Kochab (the brightest star in the Little Dipper’s bowl) was where our North Pole pointed; thousands of years from now, it will point at Vega, one of the brightest stars in the sky, 13,000 years in the future.
The main effect of this precession on temperature is seasonal, however, and has no long-term effect on an annual basis. Because the South Pole points towards the Sun close to the December solstice, orbital perihelion aligns with its summer and aphelion is close to its winter, resulting in colder winters and hotter summers compared to the Northern Hemisphere. This will change over time with a ~23,000 year period, but presents no long-term, overall temperature variations.
Over time periods of ~41,000 years, Earth’s axial tilt will vary from 22.1 degrees to 24.5 degrees and back. Right now, our tilt of 23.5 degrees is slowly decreasing from its maximum, which was reached just under 11,000 years ago, to its minimum, which it will achieve a little less than 10,000 years from now. (NASA / JPL)
2.) Axial tilt. At present, the Earth rotates on its axis at an angle of 23.5°, and that axial tilt plays a more significant role than even how close or far we are from the Sun in determining our seasons. When the Sun’s rays are more direct on our portion of the Earth, we receive more energy from the Sun; when they’re more indirect (incident at a lower angle and passing through more of our atmosphere), we receive less energy. Over the course of a year and averaged over the whole planet, our axial tilt doesn’t substantially affect how much total energy the Earth receives.
But our axial tilt does vary somewhat over long periods of time: from a minimum of 22.1° to a maximum of 24.5°, oscillating from its minimum to maximum and back to minimum again approximately every ~41,000 years. Our Moon is primarily responsible for stabilizing our axial tilt; the tilt of Mars is comparable to that of Earth, but Mars’s variations are about 10 times as great, because it lacks a large, massive moon to keep these axial tilt variations small.
Earth rotates on its axis, but its axial rotation varies by less than 2.5 degrees over time owing to the presence of a large, massive Moon. Mars, which has a similar axial tilt to Earth at present, sees variations in its tilt that are approximately a factor of 10 greater than Earth’s due to the lack of such a moon. (NASA / GALILEO)
Although the total energy received by our planet — and hence, Earth’s total temperature — isn’t affected by our axial tilt, the energy received as a function of latitude is very sensitive to it. When our axial tilt is lower, a greater percentage of the energy received by Earth is concentrated towards equatorial latitudes, while when it’s greater, less energy is received at the equator and more is incident on the poles. As a result, larger axial tilts favor the retreat of glaciers and polar ice sheets, while smaller axial tilts generally favor their growth.
Right now, our axial tilt is about midway between these two extremes, and in the process of decreasing. Our axial tilt last reached its maximum value nearly 11,000 years ago, corresponding to the end of our last glacial maximum, with our next minimum approaching in a little under 10,000 years. If natural variations were dominant, we’d expect the next ~20,000 years to favor the growth of ice sheets. As NASA’s website says:
“As obliquity decreases, it gradually helps make our seasons milder, resulting in increasingly warmer winters, and cooler summers that gradually, over time, allow snow and ice at high latitudes to build up into large ice sheets. As ice cover increases, it reflects more of the Sun’s energy back into space, promoting even further cooling.”
This, very likely, is where the notion that Earth should start cooling again comes from.
Variations in the eccentricity of the ellipse that Earth traces out around the Sun occur in ~100,000 year intervals, with maximal changes occurring over a period of every four cycles: with ~400,000 year periods. The changes in orbit shape are the only one of the major Milankovitch cycles that change the total amount of solar radiation reaching Earth. (NASA/JPL-CALTECH)
3.) Eccentricity. This effect, of all the effects caused by the dynamics experienced by Earth in the Solar System — gravitational forces, tides, angular momentum exchange, etc. — is the only one that changes the total amount of solar energy received by the Earth on an annual basis. Due largely to the gravitational tug of the gas giants, the eccentricity of Earth’s orbit (or how elongated its ellipse is, e, which is 0 for a perfect circle and approached 1 for an extremely long, skinny ellipse) varies in two ways:
- with a periodicity on 100,000 year timescales, going from almost-perfectly circular orbits (e = 0) to near-maximum ellipticity,
- and with additional slight magnifications every 400,000 years, leading to Earth’s orbit achieving its maximum ellipticities of all (e = 0.07).
Earth, right now, has a relatively small eccentricity: 0.017, which is close to the minimum value. Our closest approach to the Sun, perihelion, is only 3.4% closer than our farthest position, aphelion, and we receive just 7% more radiation from the Sun in that configuration. On the other hand, when our eccentricity is maximized, perihelion and aphelion differ by thrice that amount, with the difference in radiation received at perihelion vs. aphelion rising to 23%.
The orbits of the planets in the inner solar system aren’t exactly circular, but they’re quite close, with Mercury and Mars having the biggest departures and the greatest ellipticities. While Mars’s orbital eccentricity, at 0.09, is much larger than Earth’s at present (at 0.017), Earth’s eccentricity can achieve a maximum of 0.07, rivaling Mars and potentially causing our seasons to be dominated by orbital position, rather than axial tilt, just like Mars. (NASA / JPL)
When our orbit is more eccentric, our seasons can even become dominated by our orbital position, rather than our axial tilt. However, that’s unlikely to happen anytime soon. Right now, our eccentricity is close to the minimum, and is decreasing further: towards zero. And in general, higher eccentricity — a more elliptical orbit as compared to a more circular one — means a greater amount of solar radiation received by Earth over the course of a year.
- The maximum amount of radiation Earth can receive occurs when our eccentricity is maximized, and we can call that “100%” of maximum.
- For a perfectly circular orbit, we’d still receive 99.75% of that maximum amount.
- For where we are right now in our orbit, we receive almost that same value: 99.764%, which is presently decreasing towards that 99.75% value.
There is a slight decrease that’s in progress, but it’s so minuscule that it’s practically negligible — as are all of these cumulative effects — in comparison to the enormous changes brought on by the human-caused greenhouse gas contribution to global temperature.
The global surface average temperature for the years where such records reliably and directly exist: 1880–2019 (at present). The zero line represents the long-term average temperature for the whole planet; blue and red bars show the difference above or below average for each year. The warming, on average, is by 0.07 C per decade, but has accelerated, warming at an average of 0.18 C since 1981. (NOAA / CLIMATE.GOV)
Looking at the effects of Earth’s orbital changes quantitatively — including all three effects of precession, axial tilt, and elliptical eccentricity — so clearly illustrates the incredible conundrum facing humanity today. Because of the increased concentration of greenhouse gases, Earth’s average global temperature has increased by approximately 0.98°C (1.76°F) since 1880: an increase of approximately 0.33% in the average energy retained by the Earth. This human-caused effect has, by far, the dominant impact on Earth’s climate of all of these factors.
The increased energy retention due to atmospheric changes dwarfs the coming 0.014% decrease in received energy arising from the change in our ellipse’s shape, and overwhelms the axial tilt changes, which redistribute only an extra 0.0002% of the polar energy towards the equator with each passing year. It even dwarfs the 0.08% variation that occurs coincident with the 11-year sunspot cycle. Unless we address the human factors which currently dominate the changing climate of Earth, these natural factors — important and real though they may be — will be overwhelmed by our own recklessness.