top | item 28969194

React Docs Beta – rewritten with hooks and interactive examples

329 points| jitl | 4 years ago |beta.reactjs.org | reply

96 comments

order
[+] acemarke|4 years ago|reply
I am _so_ very excited about this! This is going to be a huge help for the community. These new docs are an incredible improvement over the old docs. In-depth tutorial and concept explanations, live editable sandboxes, coverage of key concepts and common gotchas, and much more!

See the docs repo PR [0] for background on what content is currently included, plans for further content and site improvements, and feedback on the new docs.

For why this is a big deal: the old docs were good in some ways, but very weak in others.

By far the biggest issue is that hooks were announced in Oct 2018 and released live in early 2019, but the tutorials and explanations were all still written with class components and showed older patterns, well after the community had fully adopted hooks as the standard approach. The hooks info was a totally separate section of the docs. That section was _good_, but it made it really hard to continue recommending the React docs as a good starting point for someone new to React.

The docs have also skimmed past a lot of important information, usage concepts, and info on how React itself actually works. For example:

- React's batching behavior is something that frequently trips people up, but the current docs just have a note that says "updates may be async"

- Using the hook dependency arrays correctly is vital, but the current hook docs describe it as sort of an after-thought

- There's no information on what a "reducer function" is or how to use one correctly.

That's part of why I ended up writing a 9K-word "Guide to React Rendering Behavior" post [1], and Dan wrote a similar "Guide to `useEffect`" [2] article.

Fortunately, the new docs address a lot of those concepts directly, which should really help people who are getting started.

[0] https://github.com/reactjs/reactjs.org/pull/3965

[1] https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...

[2] https://overreacted.io/a-complete-guide-to-useeffect/

[+] cageface|4 years ago|reply
All the elegance of React & hooks falls apart once you have to start worrying about performance. Managing dependency arrays is tedious and error prone and the source of many subtle bugs. Code stuffed full of memo calls is not pleasant to read. It really feels like you're doing the work that a language or complier should be doing for you.
[+] seedboot|4 years ago|reply
Congratulations I've been looking forward to starting reading this for some time!
[+] zarzavat|4 years ago|reply
I'm clearly missing something with hooks. The main selling point seems to be that your code is more "functional" because you are typing the 'function' keyword more often, but the new functions you can write are not pure functions. They are "react functions" and have all kinds of global baggage, just like component classes.

Having more impure functions doesn't do anything for me aesthetically, it might as well be a class. At least classes force you to declare (in typescript) the type of your state, with hooks it's all hidden inside. That seems less functional rather than more.

[+] travisd|4 years ago|reply
The core of it is getting closer to true "reactive" programming. If you use hooks right™, you generally don't have to worry about how to handle values over time. React does all that plumbing for you (which is why we need all the dependency arrays).

This for me is the main advantage over class components. You don't need to worry about the various lifecycle methods (including having separate methods for componentDidMount and componentDidUpdate and making sure you do all the plumbing right when your parent changes props that you weren't expecting).

IMO, React really could have benefited from devoted language syntax for this (like Svelte does) to automagically and statically track all the dependencies. But React has an ethos of being "just JavaScript" (even JSX desugars to relatively straightforward React.createElement calls, and you can treat those nodes like regular JS objects, pass them around willy nilly, etc.), so it didn't happen (and instead we have lint rules like ESLint rules-of-hooks that are designed to enforce the invariants that really the programming language should enforce).

Edit: The other nice things about hooks is their composability (and this is in fact related to what I said above). With class components, a component can have one state object, so it's hard to compose with other "mixin" type behaviors that need their own dedicated state. You ended up with weird patterns like higher order components (à la Redux withStore) that have basically ceased to exist with hooks (replaced by a useStore hook which can opaquely manage its own state under the hood).

[+] SebastianKra|4 years ago|reply
So imagine you have a class and you wan't to abstract away some stateful logic. You can use inheritance or mixins. You can use composition. You have to come up with some solution for reactivity, which means setting up observers and disposables. You might have to set up some variables for storing the emissions from those streams.

I currently have to use an Angular-like framework, and my classes usually have 10-50 lines just setting up calls to other abstractions.

Hooks simplify that: setup, teardown, state and reactivity all in a single function call.

I'm not saying they're perfect, I would probably prefer a compiled solution like in Svelte. But when has anything ever been perfect.

[+] TechBro8615|4 years ago|reply
Hooks make logic composable in the same way components make rendering composable. That composability allows for organizing code by what it does, rather than when it runs.
[+] rat9988|4 years ago|reply
It's less verbose. It makes it more readable, in my opinion. They could have implemented the very same thing with a class, but they didn't.

It's not about functional vs OOP. It's just about readability.

[+] mdoms|4 years ago|reply
Hooks are truly the most hideous API I have ever encountered. The whole thing just feels so forced and unnecessary.
[+] wheybags|4 years ago|reply
As someone who's new to react, and basically started with hooks: am I missing something? The old class based code looks so much better than the hooks magic. Is this just js people hating OO or is there something deeper?
[+] jitl|4 years ago|reply
The hooks approach is all about making the UI more incremental. I have an easier time reducing the work the computer has to do by using hooks like useMemo and useEffect compared to custom prop diffing. For example, building complex query forms over large amounts of in-memory data that do minimal async requests and re-computations when props change is much easier with hooks. useEffect/useLayoutEffect also makes behavior lifecycle for weird DOM stuff like MutationObserver easier to manage since you don’t need to spread it out in like 6 different lifecycle callbacks.

On the other hand, class components have a better developer experience for components that are mostly dumb renderers that bind a lot of event handlers - `private handleFooClick = () = > { … }` is a lot nicer than `const handleFooClick = useCallback(() = > { … }, […])` and you don’t have to worry about ordering between your methods definitions in classes. Declaration ordering between hooks is annoying, but what you get in return is incremental computation. If you don’t need that stuff, sure - use a class!

I do find more and more frequently as I’m working with class components thinking “dang, this would be much easier with hooks”, especially for tricky problems. I don’t find the opposite to be true in hook components.

[+] afavour|4 years ago|reply
It’s a better representation of what’s going on underneath but FWIW I agree with you, there are very few instances where I find hooks code that’s as readable as class-based code.

I know I’m not typical at all but hooks kind of marked the point where I lost interest in keeping up with the changes in React. I’m lucky that my job doesn’t require me to and I’ve had a great time exploring options like Vue and Svelte. Svelte in particular feels like it takes the opposite approach to hooks-based React: rather than force you to think about the way React is processing things it lets you write code the way you think about things and transpiles it into working JS.

Beyond “everyone uses it” I can find few reasons to prefer React these days.

[+] srcreigh|4 years ago|reply
If you want to see really ugly code, read the docs about Higher Order Components [0].

Hooks are better for building component abstractions than HOCs. Code which can hook into mount/unmount, can trigger re-renders via state updates, etc.

Also, dependency arrays in useEffect and useCallback are better than this kinda stuff in shouldComponentUpdate lifecycle method:

    if (prevProps.commentId !== this.props.commentId) {
      return true;
    }
    return false;
[0]: https://reactjs.org/docs/higher-order-components.html
[+] jolux|4 years ago|reply
For one thing they currently plan to maintain classes indefinitely, so if you really wanted to get started with classes you can just do that, and learn hooks later.

That said, the React docs are pretty clear about the motivation for hooks and I think that is a good place to start: https://reactjs.org/docs/hooks-intro.html#motivation.

After that, this post explains roughly how hooks actually work (in a simplified way), and why they're a more natural fit for what's happening under the hood: https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-rea...

[+] posix86|4 years ago|reply
But it's not really OO, it's some ugly mix with rules:

* don't put side-effect initialization code into the constructor * use state to render your components * don't set state directly, use setState, _unless_ in the constructor * if you want to use stores, declare a static field

You don't inherit classes, as there are many special methods, and overwriting them would mean calling super - before your method body? After? During?

Class based components only pay off if you have truly large and complex components, and that's an antipattern in react anyway. Hooks are concise, and super clear if you keep it simple (there are also additional rules not enforced by the compiler, like putting all side-effectful code into useEffect, but still).

[+] pcl|4 years ago|reply
The sense I get is that the original React model has some pretty significant complexities, especially around shouldRender and prop / state analysis, and hooks present a big improvement on that.

I don’t think that the class-vs-function divide is the fundamental reason for the problems with the old model or the improvements with the new model. Rather, I think the learnings from the original approach informed the system and resulted in a step forward.

I find that once I need to manage a nontrivial amount of state, the functional model really feels wrong — useContext, I’m looking at you! And I wouldn’t be surprised if we end up with another turn of the crank that introduces a class-based (or prototype-based) approach with a better set of abstractions at some point down the line.

[+] chadlavi|4 years ago|reply
These kids these days get better docs than we ever dreamed of. And that's a good thing.
[+] thefunnyman|4 years ago|reply
I’ve found react to be an outlier in this regard. The React docs are phenomenal and in combination with create-react-app it’s super easy to start up a new project. I can’t say the same about the majority of other frameworks I’ve encountered.
[+] h1fra|4 years ago|reply
Very excited about this release, the website is so much better and easier to read. Congrats!

(Disclaimer I work at Algolia in the Crawler team) Not to hijack this thread, but the search is now powered by Algolia custom crawler (still Docsearch but used to be a custom scrappy implem), it should match previous high level of expectation, but we'll appreciate any feedback on the relevancy.

[+] colesantiago|4 years ago|reply
Does anyone know what UI components or style this documentation uses?, I have to say the UI style is really nice and modern.
[+] yepthatsreality|4 years ago|reply
Glad to see these improvements. My previous favorite part of the older React docs was the several times looking up a lifecycle method I was partially familiar with only to see it had been deprecated for a new similar method.
[+] 999900000999|4 years ago|reply
With all the Facebook bad posts, React JS is much better with FB funding then without.

You can legitimately learn programing just from reading though the React JS tutorials. Many other frameworks lack such good documentation.

[+] ramesh31|4 years ago|reply
Very nice. I have to admit I was highly skeptical of hooks at first, but at this point I'll never go back to writing classes. Functional components are the truth.
[+] kaycebasques|4 years ago|reply
Anyone know of any issues / blog posts / etc. on "lessons learned" from the overall docs refactoring project?
[+] warpech|4 years ago|reply
'New React Docs' GitHub Issue is interesting and shines some light on the changes.

Significantly, note that it took a litle bit more than a year from the formulation of this issue to the Beta version. Knowing that there were some holy wars to be fought on the way, I don't think it's too long. Congrats to the team who worked on it!

[1] https://github.com/reactjs/reactjs.org/issues/3308

[+] acemarke|4 years ago|reply
I had asked Rachel Nabors about that a few weeks ago, and she said she had a post drafted and would put it up post-beta launch.
[+] rapfaria|4 years ago|reply
Well, indeed beta:

https://imgur.com/a/iIeoL5A

[+] cuddlecake|4 years ago|reply
Doesn't seem like a bug indicative of being beta.

The bug could obviously be fixed by looping back to 0, but the correctness is not the important part.

Though, reporting such an issue does not seem to be possible, hmm :(

[+] danabramov|4 years ago|reply
Nice find! One of the pages has an exercise where you need to fix this bug.
[+] moneywoes|4 years ago|reply
Looking to reacquaint myself with React. Should I skip over class components?
[+] evantahler|4 years ago|reply
Yeah. Most use cases just need hooks and functions now!
[+] andrewingram|4 years ago|reply
I’d say so, unless you have a particular reason to learn them. I haven’t written a class component in well over 2 years.
[+] adzm|4 years ago|reply
Don't skip over class components. There is a ton of existing code and libraries that use it.
[+] jerrygoyal|4 years ago|reply
hooks are yet to be added to new docs (only useState for now).
[+] brundolf|4 years ago|reply
useState is a hook (arguably the main hook). Maybe you meant useEffect?
[+] nathias|4 years ago|reply
why is it not called useReactDocs?
[+] anarchy8|4 years ago|reply
It really should have Typescript as well (optionally, that is)