Explain Codes LogoExplain Codes Logo

React "after render" code?

javascript
react
lifecycle-methods
hooks
Alex KataevbyAlex Kataev·Oct 29, 2024
TLDR

To execute code after rendering in React, the useEffect hook is your go-to tool:

import React, { useEffect } from 'react'; const MyComponent = () => { useEffect(() => { console.log('Hello post-render world!'); }, []); // This baby runs once after mounting return <div>I'm alive!</div>; };

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:

componentDidMount() { const div = ReactDOM.findDOMNode(this); div.style.height = `${window.innerHeight}px`; // Giving div a height, based on window height. How cool is that! }

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:

useLayoutEffect(() => { const node = ref.current; node.style.height = `${node.scrollHeight}px`; // You're as tall as you feel, they said. }, []);

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:

useEffect(() => { requestAnimationFrame(() => { // This is some next level optimization right here! }); });

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:

componentDidUpdate(prevProps, prevState) { if (prevState.windowWidth !== this.state.windowWidth) { this.adjustHeight(); // I'm always in the right shape, no matter the window size! } }

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:

state = { isContentLoaded: false, }; componentDidMount() { this.setState({ isContentLoaded: true }); // Peekaboo! }

Then in your component's render method, you can adjust the styles based on this state:

render() { return ( <div style={{ visibility: this.state.isContentLoaded ? 'visible' : 'hidden' }}> { /* Let's party when the data is ready! */ } </div> ); }

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:

this.setState({ dynamicHeight: window.innerHeight, }, () => { // Executing calculations after state update, because who says we can't have a bit of fun after work? });

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:

const myRef = useRef(null); useEffect(() => { const node = myRef.current; console.log(node.scrollHeight); // Talking about a tall story! }, []);