0% found this document useful (0 votes)
49 views

1.react Class Based Component

React class based components have several lifecycle methods that allow code to run at certain points, like componentDidMount which runs after mounting and componentDidUpdate which runs after updating. Commonly used methods include componentDidMount, componentDidUpdate, and componentDidCatch for error handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

1.react Class Based Component

React class based components have several lifecycle methods that allow code to run at certain points, like componentDidMount which runs after mounting and componentDidUpdate which runs after updating. Commonly used methods include componentDidMount, componentDidUpdate, and componentDidCatch for error handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

React Class Based Components -

componentDidMount,WillUpdate,should upate,
didcatch

Dr. RAMA ABIRAMI K,


ASSOCIATE PROFESSOR/ISE,
DSATM
Overview
• React lets you define components as classes or functions.
Components defined as classes currently provide more
features. To define a React component class, you need to
extend React.Component:

• class Welcome extends React.Component {


• render() {
• return <h1>Hello, {this.props.name}</h1>;
• }
• }
• The only method you must define in
a React.Component subclass is called render().
All the other methods described on this page
are optional.
• We strongly recommend against creating
your own base component classes. In React
components,
code reuse is primarily achieved through com
position rather than inheritance
.
The Component Lifecycle
• Each component has several “lifecycle methods” that you can override to run
code at particular times in the process. You can use this lifecycle diagram as a
cheat sheet. In the list below, commonly used lifecycle methods are marked
as bold. The rest of them exist for relatively rare use cases.
• Mounting
• These methods are called in the following order when an instance of a
component is being created and inserted into the DOM:
• constructor()
• static getDerivedStateFromProps()
• render()
• componentDidMount()
• Note:
• This method is considered legacy and you should avoid it in new code:
• UNSAFE_componentWillMount()
Updating
• An update can be caused by changes to props or state. These methods are
called in the following order when a component is being re-rendered:
• static getDerivedStateFromProps()
• shouldComponentUpdate()
• render()
• getSnapshotBeforeUpdate()
• componentDidUpdate()
• Note:
• These methods are considered legacy and you should avoid them in new
code:
• UNSAFE_componentWillUpdate()
• UNSAFE_componentWillReceiveProps()
Unmounting
• This method is called when a component is
being removed from the DOM:
• componentWillUnmount()
Error Handling
• These methods are called when there is an error during
rendering, in a lifecycle method, or in the constructor of
any child component.
• static getDerivedStateFromError()
• componentDidCatch()
• Other APIs
• Each component also provides some other APIs:
• setState()
• forceUpdate()
Commonly Used Lifecycle Methods

• The methods in this section cover the vast


majority of use cases you’ll encounter creating
React components. For a visual reference,
check out this lifecycle diagram
componentDidMount()
• componentDidMount() is invoked immediately after a component is mounted
(inserted into the tree). Initialization that requires DOM nodes should go here. If
you need to load data from a remote endpoint, this is a good place to instantiate
the network request.
• This method is a good place to set up any subscriptions. If you do that, don’t
forget to unsubscribe in componentWillUnmount().
• You may call setState() immediately in componentDidMount(). It will trigger an
extra rendering, but it will happen before the browser updates the screen. This
guarantees that even though the render() will be called twice in this case, the
user won’t see the intermediate state. Use this pattern with caution because it
often causes performance issues. In most cases, you should be able to assign the
initial state in the constructor() instead. It can, however, be necessary for cases
like modals and tooltips when you need to measure a DOM node before
rendering something that depends on its size or position.
componentDidUpdate()
• componentDidUpdate(prevProps, prevState, snapshot)
• componentDidUpdate() is invoked immediately after updating
occurs. This method is not called for the initial render.
• Use this as an opportunity to operate on the DOM when the
component has been updated. This is also a good place to do
network requests as long as you compare the current props
to previous props (e.g. a network request may not be
necessary if the props have not changed).
• componentDidUpdate(prevProps) { // Typical usage (don't
forget to compare props): if (this.props.userID !==
prevProps.userID) { this.fetchData(this.props.userID); } }
• You may call setState() immediately in componentDidUpdate() but
note that it must be wrapped in a condition like in the example above,
or you’ll cause an infinite loop. It would also cause an extra re-
rendering which, while not visible to the user, can affect the component
performance. If you’re trying to “mirror” some state to a prop coming
from above, consider using the prop directly instead. If your component
implements, the getSnapshotBeforeUpdate() lifecycle (which is rare),
the value it returns will be passed as a third “snapshot” parameter
to componentDidUpdate(). Otherwise this parameter will be undefined.
• Note
• componentDidUpdate() will not be invoked if shouldComponentUpdate
() returns false.
shouldComponentUpdate()
• shouldComponentUpdate(nextProps, nextState)
• Use shouldComponentUpdate() to let React know if a component’s output
is not affected by the current change in state or props. The default
behavior is to re-render on every state change, and in the vast majority of
cases you should rely on the default behavior.
• shouldComponentUpdate() is invoked before rendering when new props or
state are being received. Defaults to true. This method is not called for the
initial render or when forceUpdate() is used.
• This method only exists as a performance optimization. Do not rely on it to
“prevent” a rendering, as this can lead to bugs. Consider using the built-in
PureComponent instead of writing shouldComponentUpdate() by
hand. PureComponent performs a shallow comparison of props and state,
and reduces the chance that you’ll skip a necessary update.
• If you are confident you want to write it by hand, you may
compare this.props with nextProps and this.state with nextState and
return false to tell React the update can be skipped. Note that
returning false does not prevent child components from re-rendering
when their state changes.
• We do not recommend doing deep equality checks or
using JSON.stringify() in shouldComponentUpdate(). It is very inefficient
and will harm performance.
• Currently, if shouldComponentUpdate() returns false, then
UNSAFE_componentWillUpdate(), render(), and componentDidUpdate
() will not be invoked. In the future React may
treat shouldComponentUpdate() as a hint rather than a strict directive,
and returning false may still result in a re-rendering of the component.
componentDidCatch()
• componentDidCatch(error, info)
• This lifecycle is invoked after an error has been thrown by a
descendant component. It receives two parameters:
• error - The error that was thrown.
• info - An object with a componentStack key containing
information about which component threw the error.
• componentDidCatch() is called during the “commit” phase, so
side-effects are permitted. It should be used for things like
logging errors:
• class ErrorBoundary extends React.Component {
• constructor(props) {
• super(props);
• this.state = { hasError: false };
• }
• static getDerivedStateFromError(error) {
• // Update state so the next render will show the fallback UI.
• return { hasError: true };
• }
• componentDidCatch(error, info) {
• // Example "componentStack":
• // in ComponentThatThrows (created by App)
• // in ErrorBoundary (created by App)
• // in div (created by App)
• // in App
• logComponentStackToMyService(info.componentStack);
• }
• render() {
• if (this.state.hasError) {
• // You can render any custom fallback UI
• return <h1>Something went wrong.</h1>;
• }
• return this.props.children;
• }
• }
• Production and development builds of React slightly differ in the way
componentDidCatch() handles errors.

• On development, the errors will bubble up to window, this means that any
window.onerror or window.addEventListener('error', callback) will intercept
the errors that have been caught by componentDidCatch().
• On production, instead, the errors will not bubble up, which means any
ancestor error handler will only receive errors not explicitly caught by
componentDidCatch().
References
• https://
reactjs.org/docs/react-component.html

You might also like