Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the alternative to ComponentDidMount in React Server Rendered Application?

I have created an isomorphic React application. Everything works fine till I was trying to put some animations on my elements. If it was a client-side rendering app, I would do that by writing the animation function and invoke the function in componentDidMount() component lifecycle method. But unfortunately, this method won't work for SSR.

How to invoke my animation function in this case? (tried componentWillMount already, it's not working)

like image 431
Ajay Varghese Avatar asked Aug 16 '18 16:08

Ajay Varghese


People also ask

What can be used instead of componentDidMount?

The equivalent of componentDidMount in hooks is the useEffect function. Functions passed to useEffect are executed on every component rendering—unless you pass a second argument to it.

What is the difference between componentDidMount and componentDidUpdate?

The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes. Parameters: Following are the parameter used in this function: prevProps: Previous props passed to the component. prevState: Previous state of the component.

How do you avoid React componentDidMount being called multiple times?

How to avoid React componentDidMount being called multiple times. Are you seeing your React component calling the componentDidMount lifecycle multiple times? The answer to this problem is to avoid conditional rendering, and avoid adding the React prop key to the component.

Is componentDidMount deprecated?

componentDidMount isn't deprecated and is definitely still safe to use, so there's no need to add UNSAFE_ to that method. The componentWillSomething methods are the ones that seem to be on their way out.


1 Answers

By design, no lifecycle methods should be invoked when rendered by the server (except componentWillMount). This is because server side rendering is primarily for displaying site layout before data can be fully loaded and cannot really help for client side animations.

To get lifecycle methods to work on the client, simply use ReactDOM.hydrate(), which is specifically designed to be used with server rendered content using the same component on the client. This way, componentDidMount and all other life cycle methods will work as expected while still containing the server rendered content.

If you don't want to do this, and you just want to use React to generate HTML from the server, you should probably consider using a regular templating language, instead. However, if you still want to call animations without using React from the client, you should try to make your animation work with pure CSS animations.

like image 126
Kevin Raoofi Avatar answered Oct 01 '22 02:10

Kevin Raoofi