服务端渲染时是否会调用getDerivedStateFromProps钩子?
Question 1: Does getDerivedStateFromProps get called during server-side rendering?
Absolutely! When you use renderToString from react-dom/server for server-side rendering (SSR), the getDerivedStateFromProps hook does get called.
Here's the breakdown: During SSR, React creates component instances and initializes their state using the props passed to them. Since getDerivedStateFromProps is designed to sync component state with props changes—including when a component first receives its initial props—it triggers automatically during this initialization process. It’s a stateless, static hook that doesn’t depend on browser DOM, so it works seamlessly in the server environment.
Question 2: Does "instantiation" equal "mounting"? Will renderToString call the hook?
Let’s clear up the terminology first:
- Instantiation: This refers to the creation of a component instance (the JavaScript object representing the component).
- Mounting: This is the browser-specific step where the component instance is inserted into the actual DOM tree.
These are not the same—SSR never performs mounting, since it only generates raw HTML strings to send to the client, with no interaction with the browser’s DOM.
That said, renderToString does trigger getDerivedStateFromProps because it involves instantiating the component and passing it initial props. As per React’s documentation, this hook runs in two scenarios:
- After the component is instantiated (whether on the server or client)
- Whenever the component receives new props
Since SSR checks the first box (instantiation + initial props), the hook runs just like it does during the client’s initial render (before the component mounts to the DOM). Remember, only DOM-dependent hooks (like componentDidMount) are skipped during SSR—getDerivedStateFromProps is safe to use here.
内容的提问来源于stack exchange,提问作者Tomasz Mularczyk

