React Docs Beta – rewritten with hooks and interactive examples
beta.reactjs.org
beta.reactjs.org
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-...
https://beta.reactjs.org/community/acknowledgements#react-do...
(I did get to see an early alpha preview version and gave some feedback - other than that I've just been very eagerly awaiting this coming out)
React will go the way of JQuery in 5 years. We'll kindly thank it for it's contribution to the framework space and move on. No one in their right mind would pick it up for new apps over Vue, Svelte, Angular hell even Ember. Then you have the new wave of frameworks coming out. Only way that React is usable is only for the view layer with Mobx holding any other state.
To get concrete, there's no possible way this function could be automatically memoized at a library/framework level:
const myCallback = () => setFoo("bar")ReactDOM.render(element, document.getElementById('root'), {memo: true});
Just dreaming...
If a downstream component's useEffect depends on a prop that hasn't been useMemo'd, their effect will be executed on every render due to the changing reference, and there is nothing that can be done at the downstream component to alter that behavior. This means they'd have to trace the prop back to its source and refactor it to useMemo, which can be a very painful exercise as I'm sure anyone who has done it can attest to. For props that come from third party libraries, this might not even be an option, which is why pre-emptively useMemo'ing is even more crucial for reusable abstractions like shared hooks and components.
And yes, I realize that the React docs currently recommend using useMemo only as a performance optimization, not as a semantic guarantee, but I believe that ship has sailed. There is so much code in the wild today that useMemo and then pass the result to some useEffect downstream, that they can't really afford to break in practice. I think the only practical option at this point is to strengthen the original useMemo with a semantic guarantee, and then introduce a separate useMemoForPerformanceOnly (with a better name) hook that can be used to opt-out of the semantic guarantee to allow React to evict memoized results to optimize for memory usage.
I wonder why React doesn't provide a configuration/flag/option to just do this by default if anybody wants to.
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.
It's not about functional vs OOP. It's just about readability.
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).
You’re looking for solid.js
It’s “just JavaScript” like React, but with automatic dependency tracking. My understanding is that React hooks are the best React can do given backwards compatibility requirements. Reacts beast feature is it’s ecosystem.
This is more because the React team didn't care to figure out proper mixins beyond "Object.assign all the things"[0]
[0]http://raganwald.com/2016/07/20/prefer-composition-to-inheri...
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.
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...
I've read this a number of times, and none of the point make sense to me.
> It’s hard to reuse stateful logic between components
Is there some reason you can't use a `get(key)` and `set(key,value)` between class components. I don't really grok react, despite trying, so maybe there's a reason that doesn't work.
> Complex components become hard to understand
I don't understand what the hard part is supposed to be here. If you have a method that's dealing with too many concerns, you can just add methods, and then call those.
> Classes confuse both people and machines
`this` is pretty confusing in javascript, but yet that's the language react is targeting. And it's no less confusing in prototype-based objects. And after having tried to learn both hooks and `this`, it certainly doesn't seem like hooks are conceptually easier than `this`.
Probably my fundamental problem with hooks is trying to understand which state goes with which component-function invocation. It just seems like dark magic that usually works. I've tried to read the implementation to figure it out. It seems to depend on the famous DOM diff feature. It was about at that point that I lost the plot.
So, I know I'm an outlier, but class-based components just make sense to me. They can be complex, but fundamentally comprehensible. Function components seem like a fake simplicity that's masking a complexity that I've yet to figure out.
You can and the hooks way is better.
The class based components way is to wrap component in a HOC. The common state is stored in the HOC. The HOC passes the state to the component via props. This can include functions, so maybe your component can call `this.props.reloadApi()`, which changes HOC state, which results in new props sent to your component.
The hooks way is described here. [0]
What's wrong with Higher-Order Components?
One answer is that it's weird to call something a "component" which doesn't render any UI. In other words, why is an interface to access remote data a "component"?
Another answer is that HOCs break the diff algorithm without special care see. [1]
[0]: https://reactjs.org/docs/hooks-custom.html
[1]: https://reactjs.org/docs/higher-order-components.html#dont-u...
Maybe I'll try implementing this to show what I mean/learn why it wouldn't work.
If yes, the reason you can't just do that is because if that is done naively then components using `get()` won't know that they need to re-render when a `set()` is called somewhere else.
Not done naively and you do have global stores built for this, like Redux or MobX, which handle this gracefully and (at this point) use hooks under the hood and in the dev-facing API to accomplish this.
Tbh this is also now built-in to React with the `useContext()` hook, which allows you to do the same. `useState()` should really only be used for local-to-a-component level state (though technically you can obviously pass down the state/setter to any child components, but given the above I find it's frequently better to `useContext()`).
https://codepen.io/tomtheisen/pen/NWvdXyJ
I already like it better than hooks. Everything's out in the open. No magic or hidden dependencies.
// this could be made to track actual depencies with more granularity
subscribe(() => this.forceUpdate())
You're well on your way to building a decent system here...I guess if you don't pass your dependencies as an array to a function called useEffect, you aren't using hooks. Win!
And if you need a specialized function to only update 1 component instead of all of them, just make sure it isn't returned by a dastardly magical function called useState.
You joke, but yes. Also, you don't have to follow these. https://reactjs.org/docs/hooks-rules.html
And you don't have to rely on the diff remembering which state goes to which widget. To its credit, it seems to do it right at least 99% of the time.
I recognize I'm tilting at windmills here. React is a juggernaut, and many people love it. In fact, many people like the exact things that I don't. And that's ok.
Order of dispatch to subscribers seems like it create similar problems, although it would be fully deterministic, rather than a race.
Anyway, thanks for your insight.
You're largely right but this part is mostly wrong in practice because of async. You can create race-like conditions very easily with promises/async if you're not careful.
> Order of dispatch to subscribers seems like it create similar problems, although it would be fully deterministic, rather than a race.
Yes, that's closer to what I meant. Not a data race, but you could end up in a loop.
[0]https://reactjs.org/blog/2016/07/13/mixins-considered-harmfu... [1]http://raganwald.com/2016/07/16/why-are-mixins-considered-ha... [2]http://raganwald.com/2016/07/20/prefer-composition-to-inheri...
https://ui.dev/why-react-hooks/
I also discussed some of the tradeoffs in a conference talk and blog post:
https://blog.isquaredsoftware.com/2019/07/blogged-answers-th...
https://blog.isquaredsoftware.com/2019/09/presentation-hooks...
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.
It didn't help that my first foray into hooks was trying to build a simple clock with `setInterval`:
https://overreacted.io/making-setinterval-declarative-with-r...
I really need to give Svelte a try.
While I love working with hooks and do so daily, I definitely felt some remorse for those now having to figure out when and how to use memoization, dependency arrays, useCallback, etc, etc etc. React in its first formulation was utterly simple and beautiful.
In defense of hooks however, it's good to keep in mind that now you can do a lot more than you could, and being able to share business logic so easily across an application is an elegant abstraction.
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.htmlI generally like shaping my components as functions first and use hooks because I have to in order to do this but definitely not because I find them easier to understand than component lifecycle methods (even if they may be less verbose).
To me, hooks are the ugly part, writing component as a single function is the part that makes it worth it.
Never found HOC ugly, it's a normal function, not a magic one that hooks into React internals. Anyone familiar with OOP also regcognizes it as adapter. I think people tend to confuses syntactical simplicity with conceptual simplicity. But even syntactically, I don't find hooks simple once we pass the toy code examples.
> Hooks are better for building abstractions than HOCs
HOCs are more explicit, they change the props signature of the component. So if you like magic, you'd prefer hooks.
Hooks are not better abstraction, they are better building blocks because they compose more nicely.
A good abstraction is something you can pass around and use liberally without knowing the inner working. You can pass a HOC around and put it in conditional etc. Can't do that with hook because the inner working prohibits that and you are required to know such caveats.
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.
But for some reason, picking someone else's class component and working on it feels much easier than someone's functional component.
I 100% agree with the last statement, most problems feel easier to write with hooks than with class components.
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.
* 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).
(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.
The "design" is the theme provided by, you guessed it, tailwind css.
I didn't know that taiwind also includes a default theme
I'm not fond of the way it's getting shoved down everyone's throat. Why is it that people won't shut up about their crappy choice of software development tools. Who cares.
I replied to someone who brough it up
> off-topic
You do realize this is a React discussion?
> There isn't a single example of it being "shoved down throats"
Hey sorry I replied with the wrong tone, but imagine you don't know that tailwind also comes with a style, someone asks about the style or specific component lib or whatever, you see a reply that "it's tailwind", which to you must be as helpful as answering with "it's css"
You can legitimately learn programing just from reading though the React JS tutorials. Many other frameworks lack such good documentation.
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!
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 :(
An official "Using React with Typescript" doc that shows good patterns for typing props and state would be nice though.
https://react-typescript-cheatsheet.netlify.app/
But yes, I'd love to have some of this info added to the official docs as well.
As an FYI for later reference, Lenz Weber has a Remark plugin that compiles TS to JS in code samples - we use that in the Redux Toolkit docs. I think Orta Therox may have something similar going on with his "Shiki Twoslash" tooling, but not entirely sure.