12 Weeks of React (part 1)
Intro
I want to deepen my knowledge in React.
This week I started reading the docs, from the very beginning, sequentially. While the basic docs are great for beginners and they sparked some thoughts, I didn't get much value from reading them. Next week I'll go through parts that I want to improve my knowledge on or not familiar with.
I will be posting my comments, thoughts and ideas that I wrote down about what I read, explored and played with.
React is mostly writing JavaScript
The Quick Start section puts an emphasis on the fact that you use regular JavaScript inside React and JSX and includes a lot of reference links to MDN and other sources for learning JavaScript.
Indeed, the fact that you can use ternary operators, mapping through a list to create a list of elements and in general escape from JSX into JavaScript by using curly braces, gives it a much closer feel to writing regular JavaScript.
Also, it allows JSX to stay very minimal compared to other templating languages. It doesn't require any special directives like in Angular or Vue. Instead, plain JavaScript can be used.
State
Try to reduce state as much as possible. When possible, derive information from existing state. This reduces the moving parts in the component and makes it much easier to change, debug and understand.
When you call the "set" function that is returned from
useState
, it tells React to start a re-render. This will
cause the child components to re-render as well.
children type
Most of the places that talk about the recommended type for the
children
prop advice to use React.ReactNode
.
Generally, this is a good advice, but I personally prefer to use more
strict typing and use React.ReactElement
when possible. For
example, when having a set of layout components which should get another
element as children
.
Another reason to why I prefer a more strict approach is because
React.ReactNode
allows boolean
,
null
and undefined
. If you don't have these
allowed as children, you reduce the risk of passing them by mistake
because of some conditional inside your JSX that might result in an
unwanted result.
JSX
React must return a single wrapping element because under the hood JSX
is being transformed into a JavaScript object. And because a React
component is a function, and a function can't have multiple returns,
React component can't return multiple JSX elements. Instead, it must
have one tag or Fragment
to wrap them all.
Because JSX is transformed to JavaScript, and in JavaScript we can't
define variables with a hyphen or using reserved words, we can't use
props with a hyphen or a reserved words like class
. This is
why we write onClick
or className
.