0

69 Lessons from the New React Docs

 1 year ago
source link: https://sebastiancarlos.medium.com/69-lessons-from-the-new-react-docs-1345ebcaf880
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

69 Lessons from the New React Docs

1*2MQasatOm2BB4n_VZJI49w.png

Sexy new React docs were recently shared on the official react website.

The React team is making a final pass before fully switching over but — at the time of writing — all of the commonly used modern APIs are documented, making it the best way to learn the framework.

0*VpL6NOOEPGg2svF6

React veterans out there know that to be a true React grandmaster, you need to follow every React team member on Twitter to make sure you don’t miss any precious nuggets of information.

Not anymore! All that esoteric knowledge is now available in an easy-to-read format. Ferocious kids coming from behind will take your jobs thanks to the new React docs!

Your only chance to stay ahead is to humble yourself, sit down, and read every single word in the new docs.

But fear not, for I have selflessly taken one for the team and already broke it all down for you. Here’s what I’ve learned:

1. React was originally created by Jordan Walke.

Today, Jordan Walke doesn’t work at Facebook anymore. His recent tweets suggest that he’s really into OCaml, a functional language. I sincerely appreciate that he used his functional mind to improve web development.

2. React has 10 team members.

The only way to join the React team is to save the life of a React team member. So far, this has only happened once, when Dan Abramov was caught in a while-loop.

3. The docs use CodeSandbox for their interactive code examples.

The docs also mention that React is supported by several other sandbox services; They explicitly name CodeSandbox, StackBlitz, and CodePen.

4. The new docs take a page from Vue on explaining the different use cases of React.

From “adding some interactivity” to “more complex apps” and even “large apps”, the new docs do a great job at mapping out the different levels of React usage.

5. Adding React to a simple HTML page is easy. It doesn’t even require a build step.

Just add React as a script tag, write a component, and render it on a root. If you want to add JSX support, you can set up a simple build step with babel-cli.

6. You can have multiple React roots.

Again, this is useful if you want to add a few interactive components to a static HTML page. You can simply create a root for each component, instead of creating a root for the full document. Yet, the docs don’t clarify if it’s possible to share information between components on different roots.

7. The new docs still recommend the godawful Create React App.

Create React App might be convenient and unopinionated, but it’s a pile of outdated trash that never fixes important bugs. Just take a look at the Github issues if you don’t believe me. Luckily, the docs also recommend popular alternatives like Vite and Parcel.

8. Next.js is recommended for production-ready projects.

No surprises here. Next.js is good, especially now that it allows more flexibility on page layouts. Other recommendations are Gatsby, Remix, and Razzle.

9. There’s a fine list of tool recommendations to build your own toolchain.

If you want to fly solo, the docs suggest a sensible and trendy list of options. A pleasing surprise to me was that there’s no mention of Lerna, which makes sense after recent debacles. Instead, the recommendations for monorepos are Nx and Turborepo.

10. The recommended editors are VS Code, WebStorm, Sublime Text, and Vim.

No big surprises there. I would only add that any JetBrains editor is up to the task, not only WebStorm. Also, Sublime Text is a meme, Dan Abramov only mentioned it because he still feels bad about that time on a conference talk when the Sublime Text pop-up for buying a licence appeared on screen.

Also, Vim’s website looks straight out the 90s, making the editor literally unusable. It will probably be replaced by NeoVim in the docs in a few years.

11. ESLint is required to properly use React, don’t kid yourself.

As it stands, any sane use of React requires the eslint-plugin-react-hooks to be running at all times. In the future this might be implemented on Rome, a compiler step, or some other tool.

12. Prettier is king.

No surprises here. The docs encourage you to use prettier or else, and that’s a good thing. If your codebase uses both ESLint and prettier, the preset eslint-config-prettier is recommended so that ESLint is only used for catching logical mistakes, letting daddy Prettier do all the important work.

13. There’s no React Developer Tools browser extension for Safari.

There’s one for Chrome, Firefox and Edge.

To debug on Safari, there’s a workaround involving the standalone react-devtools npm package, which can also be used to test React Native apps.

14. React apps are made out of components.

The docs blatantly tell you that the main abstraction of the framework is components. What can I say about the mighty MVC killer that hasn’t been said before?

They explicitly say that “A component can be as small as a button, or as large as an entire page,” and that it’s “components all the way down.” Isn’t that beautiful?

15. To learn about JavaScript, the docs recommend MDN and javascript.info.

I was not aware of javascript.info, but it’s open-source and looks pretty legit.

16. They recommend an online tool to convert HTML to JSX

This can be useful if you start from a lot of HTML. It’s needed because JSX is stricter than HTML. For example, JSX requires closing tags. Here’s the tool.

That tool is a goldmine by the way, as it includes SVG to JSX, CSS to Tailwind, and much more.

17. React does not prescribe how to add CSS.

In the simplest case, you’ll add a <link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add style to your project.

18. You can think of curly braces in JSX as an “escape hatch” into JavaScript.

It’s a nice way to think about them. You can put curly braces in the value of JSX attributes, or inside the JSX tag content.

Curly braces are “a window into the JavaScript world.”

19. The ? and && operators are recommended if you want conditional rendering inside JSX.

It’s nice to see that a tradition as old as time is still recommended. The amount of perverse satisfaction you get from using those operators is unrivalled.

20. The “key” attribute is clearly explained.

An often confusing term, key, is explained pretty well on the new docs. It’s so good that I’m gonna copy-paste the entire section here:

For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React will rely on your keys to understand what happened if you later insert, delete, or reorder the items.

21. The docs are very good at explaining what’s a rule and what’s a convention.

For example, they explain that setState returns two things, and it’s only by convention that we call them [something, setSomething].

As another example, they explain that it is common to name event handlers as “handle” followed by the event name. (onClick={handleClick}, onMouseEnter={handleMouseEnter}, and so on.)

In contrast, Hooks are functions that, as a rule, must start with “use”.

22. “If you want to use hooks in a condition or a loop, extract a new component and put it there.”

You heard it here first.

The new React docs go hard on the fact that hooks are top-level only. If you feel inclined to put a hook inside a condition or loop, that means that you need to create a new component.

What’s that? You don’t like components? Listen here you little junior developer, if you don’t like components, you can GTFO! This is a component-based framework!

Hooks are functions, but it’s helpful to think of them as unconditional declarations about your component’s needs. You “use” React features at the top of your component similar to how you “import” modules at the top of your file.

23. “Lifting state up” is front and center in the docs.

The famous refactoring pattern is so common that it’s explained in full detail on the “Quick Start” page. This should probably keep those peskier junior devs in check.

24. Turning a UI mockup into a component hierarchy is a creative process.

The docs don’t shy away from the fact that, given a UI mockup, there’s no one right way to turn it into a set of React components.

However, they encourage some common-sense guidelines, like “a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.”

25. It’s ok to be top or bottom.

When making a component hierarchy, the docs mention optional techniques like “building a static version first,” and they explore the distinction between building “top down” by starting with building the components higher up in the hierarchy or “bottom up” by working from components lower down.

26. Minimal state is cool.

The docs really emphasize the DRY (Don’t Repeat Yourself) principle when it comes to state. In particular, there’s no need to create new state when it can be computed from existing state.

Looks like the React team have been in contact with the same kind of data hoarding that I have seen in other developers.

27. Props vs State is explained clearly.

“Props are like arguments you pass to a function,” while “State is like a component’s memory.”

28. It’s ok to create a new component solely for holding shared state.

If you can’t find a component where it makes sense to own the state that’s used by several children, it’s ok to create a new one.

29. Hooks are called hooks because they let you “hook into” a component’s render cycle.

It’s always good to know what you are hooking into. Now you know.

30. In a sense, React actually uses “two-way data binding.”

Two-way data binding was the revolutionary solution of the currently-pagan framework Angular. Purist might be surprised to know that React does pretty much the same thing because it uses both “one-way data flow” and “inverse data flow.”

“One-way data flow” is the passing of data from the top to the bottom of the component hierarchy. “Inverse data flow” happens when a component deep in the hierarchy needs to update state at the top (usually because of user input.)

The catch, and the reason why React is not technically “two-way data binding,” is because React is very explicit about “inverse data flow”: The developer actually needs to write onChange event handlers.

31. The docs recommend the component libraries Chakra UI and Material UI.

Yes, in that order. Chakra UI is recommended before Material UI.

As an extra offense, Material UI is not even the current name. These days it goes by MUI as an attempt to distance itself from being a library tied to a specific artistic movement.

32. React has a philosophy of “interactivity first.”

Purists have recently claimed that the web is first and foremost a document sharing platform, and that interactivity should be secondary.

The React team strongly disagrees, and they make it clear on the new docs. I’ll just copy-paste what they have to say about it because it’s delightfully savage:

“Traditionally when creating web pages, web developers marked up their content and then added interaction by sprinkling on some JavaScript. This worked great when interaction was a nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity first while still using the same technology: a React component is a JavaScript function that you can sprinkle with markup.”

Linux boomers are recommended to apply aloe to the burn.

To be fair, the docs make it clear that React can also be used to “add sprinkles of interactivity.”

33. In React, rendering logic and markup live together.

Sure, “interactivity first,” but another guiding principle stated in the docs is that logic and markup should be together. This is good because it “ensures that they stay in sync with each other on every edit.”

34. React takes no side on the “default vs named exports” debate.

To their credit, they succinctly explain the downside of default exports, saying that “you could write import Banana from './button.js' and it would still provide you with the same default export.”

Yet, their final say on the matter is just the observation that “People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.”

They also don’t shy away from having “one default export and numerous named exports.”

35. Never define a component inside another component!

According to the docs, it’s technically possible. But it’s very slow and causes bugs. Instead, define every component at the top level.

36. It’s ok to make components even if they are not reusable.

After all, React is “components all the way down,” so there will always be a top-level “app component.”

But it’s also ok to have other one-off components because “components are a handy way to organize UI code and markup, even if some of them are only used once.”

37. They explain why a component can’t return more than one element.

It’s because “JSX under the hood is transformed into plain JavaScript objects. You can’t return two objects from a function without wrapping them into an array.”

But fear not, for you can return two JSX tags by “wrapping them into another tag or a Fragment.”

38. aria-* and data-* are the only JSX attributes written with dashes.

This is for historical reasons.

In general, everything in JSX is camelCase, even inline style properties, because JavaScript has limitations on variable names.

Additionally, since class is a reserved word, in React you write className instead.

39. “Double Curlies” is an official term.

It’s the explicit name for passing a JS object in JSX, in which you must wrap the object in another pair of curly braces: {{}}.

It’s not a special syntax, it’s just a JavaScript object tucked inside JSX curly braces.

Not to be confused with the “vagina syntax” when returning an object from an arrow function: ({}).

40. The props you can pass to HTML tags are predefined.

For example, “className”, “src”, “alt”, “width”, and “height” are some of the props you can pass to an <img> tag.

But you can pass any props to your own components.

41. If you are spreading all the time, you might be behaving immorally.

There’s nothing wrong with spreading.

Some components forward all of their props to their children. Because they don’t use any of their props directly, it can make sense to use the concise “spread” syntax: {…props}

However, the docs warn to “Use spread syntax with restraint. If you’re using it in every other component, something is wrong. Often, it indicates that you should split your components.” Careful who you spread for

42. Some components have a “hole” that can be “filled in.”

You can think of a component with a children prop as having a “hole” that can be “filled in” by its parent components with arbitrary JSX.

You will often use the children prop for visual wrappers: panels, grids, and so on.

43. Props are not always static.

A superficial understanding of the difference between state and props might make you think that props don’t change.

Not so! A parent component might have state that changes over time and passes it down to a child component as props.

However, from the point of view of the child component, props are “immutable” — a term from computer science meaning “unchangeable”

So, when a child component needs to change its props (for example, in response to a user interaction or new data) it must “ask” the parent component to generate and pass “new props” by using the aforementioned “inverse data flow.”

We can say that props are read-only snapshots in time: every render receives a new version of props.

44. The docs recommend to use ternary operators “in moderation.”

They are ok to conditionally render within JSX, but “If your components get messy with too much nested conditional markup, consider extracting child components to clean things up.”

If junior devs insist on creating a spaghetti sauce of ternary operators, consider sending them to the React docs, or here:

45. Don’t put numbers on the left side of &&.

Old timers know this one.

If you use && for conditional rendering, you’re gonna have a bad time with 0. You will likely end up with a small unstyled zero new to your shinny sans-serif material UI.

Mathematicians hate it.

46. Sometimes it’s best to avoid shortcuts and just conditionally assign JSX to a variable.

Ternary operators and &&s are nice, but if they get in the way, you might as well use old school variables to hold the conditional JSX.

I’m glad that the docs plainly say that it’s ok to write normal JavaScript. Sugar is good, but bitch please, vanilla JS is sweet enough.

47. The docs recommend “crypto.randomUUID()” or a package like “uuid.”

Yes, they recommend crypto.randomUUID() before the “uuid” package.

I never heard of that native crypto library before, but it looks solid. I should sell all my Bitcoin and buy randomUUID.

If I were the maintainer of the “uuid” package, I would start looking for a new job. These docs just ended their entire career.

48. Your components won’t receive key as a prop.

It’s only used as a hint by React itself.

If your component needs the ID that was used as the key, you have to pass it as a separate prop too.

49. React assumes that every component you write is a pure function.

Don’t go around doing impure things behind React’s back. React is designed around the concept of pure functions.

A pure function has the following characteristics:

  • It minds its own business. It does not change any objects or variables that existed before it was called.
  • Same inputs, same output. Given the same inputs, a pure function should always return the same result.

50. Detecting impure calculations with StrictMode.

If you are in strict mode, every component will be rendered twice. This is to detect if you are a naughty boy.

51. Not everything is pure on React ;)

I’ll let you in on a little secret, all of us React devs do impure things all the time. And we love it!

While functional programming relies heavily on purity, at some point, somewhere, something has to change. That’s kind of the point of programming!

So, we have our little secret spots on React where we can do whatever we want. We do things differently “on the side.” Tee-hee-hee!

In React, side effects usually belong inside “event handlers,” from which you are free to modify state. Even though event handlers are defined inside your component, they don’t run during rendering! So they don’t need to be pure.

If you’ve exhausted all other options and can’t find the right event handler for your side effect, you can still attach it to your returned JSX with a “useEffect” call. This tells React to execute it later, after rendering, when side effects are allowed.

52. They link to a Medium article about design systems.

They really do. Here it is:

Congrats to Audrey Hacq, you really made it into the React docs. Can’t wait to see the movie adaptation of your article.

53. They say that event objects are usually called “e” by convention.

Bad move, React Docs, bad move.

I’ve been fighting junior devs for years to write those as “event.”

What am I gonna do now, React? Tell me, what the fuck am I supposed to do with all those “e”s on my otherwise fucking pristine codebase?

54. Event handlers are just functions that you pass as props.

There’s nothing special about them.

Except of course that they are meant to respond to interactions like clicking, hovering, and so on.

Which means that every event handler, at the very bottom of the React component tree, will land on one of the built-in handlers like “onClick” on some HTML tag like “button”. Just like every thought originates at the endocrine system.

55. You should name event handler based on app-specific concepts.

When your component supports multiple interactions, you might name event handler props for app-specific concepts. For example “onPlayMovie” and “onUploadImage”.

56. The docs remind you that capture and propagation exist.

If you were lucky enough to work on high-level stuff and rely solely on event handlers, the React docs are there to remind you that the complete hell of DOM event propagation is still alive. May God help us all.

57. e.stopPropagation() stops propagation.

It does.

58. e.preventDefault() prevents default.

How nice.

59. Local variables don’t persist between renders.

When React renders a component a second time, it renders it from scratch — it doesn’t consider any changes to local variables.

60. Changes to local variables won’t trigger renders.

Few things trigger renders. Changing local variables ain’t one of them, buster.

61. To update a component with new data, two things need to happen.

First, we need to persist the data between renders. Second, we need to trigger React to render the component with new data (re-rendering).

Here’s where the useState Hook comes in. It provides those two things:

  • A state variable to retain the data between renders.
  • A state setter function to update the variable and trigger React to render the component again.

Could this be done in a simpler way? Sure, but this isn’t Svelte, bucko. This is React, we live close to the metal and we like it like that. No magic on my JavaScript.

62. State is private to the component.

If you render it in two places, each copy gets its own state.

This might seem silly and not worth mentioning, but it can trip you up the first times using React. Specially when using useState, which is something that you have to import, and importing can feel scary because who knows what’s on the other side.

63. Triggering, rendering, and committing.

These are the three main events in a component lifecycle:

Triggering a render is queueing React to render a component as soon as it’s not too busy doing something else, like wasting CPU cycles.

Rendering is running your component and obtaining the result.

Committing is getting down and dirty and actually applying the result of rendering into the infernal machine of the browser DOM API, using contraptions like the createElement method.

63. There are two reasons for a component to render.

  1. It’s the component’s initial render.
  2. The component’s (or one of its ancestors’) state has been updated.

That’s it.

But how about…? Nope.

64. There are ways to increase performance, but thread carefully.

The default behavior of rendering all components nested within the updated component is not optimal for performance if the updated component is very high in the tree.

If you run into a performance issue, there are several opt-in ways to solve it, but don’t optimize prematurely!

65. React is smart. Maybe smarter than you!

For re-renders, React will apply the minimal necessary operations (calculated while rendering!) to make the DOM match the latest rendering output.

This right here is React’s claim to fame. Initially called the Virtual DOM or “the diff,” nowadays it’s just referred as “that thing React does,” and no questions are asked because the implementation is so obscure and arcane that you might as well apply to join the Illuminati.

66. React only changes the DOM nodes if there’s a difference between renders.

This might be one of the coolest thing ever.

Let me be clear here: Even if a component re-renders because something changed, React will only commit changes for those DOM elements that changed!

Every unaffected DOM element within the re-rendered component will be let at peace! Jesus fucking Christ! Who ever thought of that? Those React folks really had a big brain moment, Jesus Christ!

67. State is moody. It’s not like regular variables.

State might look like regular JavaScript variables that you can read and write to. However, state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render.

This is because “rendering” is actually taking a snapshot of the UI in time. Its props, event handlers, and local variables were all calculated using its state at the time of the render.

Unlike a photograph or a movie frame, the UI “snapshot” you return is interactive. It includes logic like event handlers that specify what happens in response to inputs.

So here’s the catch: You can’t change state from an event handler and then expect to read the updated value from the same event handler, because you are still trapped on the same snapshot in time. Setting state only changes it for the next render.

You might be wondering, what do I care? What kind of monster would try to read the state that was just updated?

You would be right, this is a very unimportant piece of information, and you would do well to forget everything you just read, unless you plan to impress nerds at React meetups.

68. A state variable’s value never changes within a render.

Actually, the previous point is not so unimportant.

Just remember that, whatever you do, even if you wrap a console.log into three setTimeouts, you will never escape your render snapshot. The updated state is a privilege reserved for future renders. Abandon all hope.

69. Just have fun.

At the end of the day, just enjoy yourself.

If you’re ever having a bad time, just remind yourself that at least it’s not jQuery.

Closing thoughts

Folks, let me tell you something, when I was first starting off my programming career, I would’ve never thought that the React docs would be this good.

They were always good, but they were never this good.

I remember when the only way to learn about React was to go to those fancy conferences and mingle with the cool hackers. You could count yourself lucky if they didn’t hack your Palm Pilot in retaliation.

So I encourage you, young and old, to take some time off your day and read the new React docs.

And maybe, just maybe, you’ll find that computer programming is the activity that will bring peace and prosperity to our world.

But most importantly, you’ll have fun. And that’s what it’s all about. May the force be with you.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK