DEV Community

Cover image for SSR-Proof Effects: Control Client-Side Lifecyles /w some React Magic
Mike Vardy
Mike Vardy

Posted on

SSR-Proof Effects: Control Client-Side Lifecyles /w some React Magic

Cover Photo by Anatvida Sukchanta on Unsplash

When working with React on a project using Sever Side Rendering (SSR), you might often encounter situations where you need to perform certain actions after your component has been rendered on the client side. However, traditional hooks like useEffect or useLayoutEffect can sometimes execute their effects both on the server and client side, leading to suboptimal behaviour during server-side rendering (SSR).

Enter the useClientLayoutEffect custom hook – a solution that empowers you to control when an effect should run exclusively on the client side.


The Benefits

Client-Side Precision
Unlike regular effects, useClientLayoutEffect ensures that your code is executed solely on the client side, avoiding any unnecessary server-side execution.

Optimized Performance
By avoiding unnecessary server-side effects, your application's performance can be enhanced, resulting in faster load times and smoother user experiences.

Consistent Behaviour
This custom hook maintains the familiar structure of React's effect hooks, making it easy to integrate into your existing components and workflows.


Use Cases for useClientLayoutEffect

DOM Measurements
When you need to measure elements or perform layout calculations, using useClientLayoutEffect guarantees that your calculations are based on the actual client-rendered DOM, eliminating inconsistencies.

Third-Party Integrations
Integrating third-party libraries or widgets that depend on the window object becomes seamless, as the effects will only be triggered when the necessary client context is available.

Animations and Transitions
Applying animations and transitions often requires access to the client-side rendering engine. With useClientLayoutEffect, you can ensure animations are smoothly initiated without SSR-related hiccups.


And the code:

import { useLayoutEffect } from 'react'
/**
* A custom hook that behaves like `useLayoutEffect` but waits until
* the component is on the client side and the `window` object is
* defined before executing the effect.
*
* @param {function} effect - The effect function to run.
* @param {Array} deps - An array of dependencies for the effect.
*/
const useClientLayoutEffect = (effect, deps) => {
useLayoutEffect(() => {
if (typeof window !== 'undefined') {
return effect()
}
}, deps)
}
// Usage
const App = () => {
useClientLayoutEffect(() => {
// This code will only run on the client side after the
// component is mounted and the window object is available.
console.log('Component mounted on the client side.')
return () => {
// Cleanup code here
}
}, [])
return <div>Your component content here</div>
}

Whether you're measuring elements, integrating external libraries, or orchestrating animations, useClientLayoutEffect empowers you to craft components that are not only functional but also optimized for a smooth user experience. It just might be a tool worth adding to your React hooks.

So there you have it, a dynamic solution to ensure your effects are in sync with the client-side rendering cycle, leading to a more polished and efficient React application.

Happy Coding!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay