12 Weeks of React (part 2)
Intro
This week I kept reading the docs sequentially, but skipped the parts that I found basic or am familiar with. As I progressed through the docs, I found more and more interesting bits of information. So I decided not to jump around and keep with the sequential approach.
TIL #1
It turns out that like DOM, there is also CSSOM, or CSS Object Model.
You probably used it without even knowing about it. For example, it's
when you manipulate styles of a DOM element with JavaScript via it's
style
property.
But, if you try to read values via style
, you won't get any
if they were defined with CSS. For this you can use the
window.getComputedStyle
method to get the actual styles of an element.
React render tree
You won't see any HTML tags in the tree because it is composed only of React components.
This is indented behavior because React can be ran on multiple
platforms, and the HTML tags could be some other platform specific
primitives like UIView
in iOS.
TIL #2
If you want to catch an event from a child, even if they stopped
propagation, you can append Capture
to the event handler.
TIL #3
You can use the
inset
CSS property as a shorthand for
left: 0; right: 0; bottom: 0; top: 0;
State
Changing local variables won't trigger a re-render.
Hooks rely on stable call order, this is why you must follow the lint rules for hooks.
In the following example, A and B will yield a different result
In A, the state will be incremented only by 1, but in B it will be incremented by 3.
This is because in A, each call to setCount
is using the
current count
value, so if count === 0
, then
each call will actually be setCount(0 + 1)
.
In B on the other hand, we ask from React the current state, so in the
first call if count === 0
we will get c
as
0
, on the second call as 1
(because we already
incremented it once) and so on.
Imperative vs Declarative
Entering a taxi and telling the driver where to turn on each intersection is imperative. Entering a taxi and telling the driver the destination is declarative.