React "after render" code?
To execute code after rendering in React, the useEffect
hook is your go-to tool:
This presents a convenient way to perform actions that depend on the component and its children having been rendered, such as manipulating the DOM or retrieving dimensions of elements.
Using lifecycle methods for "after render" tasks in class components
In class components, componentDidMount
is the method for carrying out actions after the initial rendering:
Immediate effect and layout measurements with useLayoutEffect
Functional components offer the useLayoutEffect
hook. When it's a matter of measuring layout or getting an instant effect before the browser gets to paint, useLayoutEffect
is your star player:
Performance optimized updates with requestAnimationFrame
During the useEffect
or useLayoutEffect
, requestAnimationFrame
can be used to synchronize DOM measurements and updates with the browser's next painting cycle. This will save you from reflow and repaint costs and optimize the performance:
Adapting to changes with componentDidUpdate
With class components, changes to the component or its props can trigger the componentDidUpdate
method. This is the place to handle size adjustments to elements, perhaps in response to a window resize:
Managing visibility through preprocessing
To avoid content flickering or layout shifting, you might want to initially set an element’s visibility to hidden and then adjust dynamically post-render:
Then in your component's render method, you can adjust the styles based on this state:
Mitigating side-effects with callbacks
Sometimes after rendering, we might want to alter state or chin-stroke with some additional calculations. The setState
method in React accepts a callback function:
Accessing the DOM directly with refs
Refs provide a way to access DOM nodes or React elements that have been rendered. After render, refs can be used to read values such as the scrollHeight of an element:
Was this article helpful?