under React
Let's review the rules of React Hooks, and how you can fix the "Hooks can only be called inside the body of a function component." error.
under React
Learn how to properly unmount React components when using React Hooks.
under React
Let's take a look at how you can fix this common error in React.
under React
Learn how to fix the "Rendered fewer hooks than expected." error with React Hooks.
under React
React Context can be more than just global state in an app. I like to think of Context as "encapsulated state".
under React
React error boundaries allow you to prevent your React application from completely crashing in the event of an error in your code.
You can read more about React's error boundaries on their documentation page.
The key point to understand when using error boundaries is this snippet from the docs:
catch JavaScript errors anywhere in their child component tree
Specifically, "component tree". If you try to use Error Boundaries in the following way, none of your errors will be caught:
1function SomeComponent() {2 return (3 <CustomErrorCatcher>4 {invalidVariable}5 </CustomerErrorCatcher>6 );7}
In the example above, CustomErrorCatcher
is our class component that implements our error boundary logic.
The code that is throwing an error, {invalidVariable}
, is rendering inside the CustomErrorCatcher
component, instead of in a child component. This is what prevents the error boundary from catching the error. The error boundary _will only_catch errors in child components.
So instead, I recommend you do something like this at the top-level of your application:
1function Root() {2 return (3 <CustomErrorCatcher>4 <App />5 </CustomErrorCatcher>6 );7}8ReactDom.render(<Root />, document.getElementById('app'));
This way your entire application is wrapped in an error boundary, in the event that any of your components throw an error.
Hopefully you found this article useful! If you did, share it on Twitter!
Found an issue with the article? Submit your edits against the repository.