Resolves to useEffect() on the server and useLayoutEffect() on the client.
- Use
typeofto check if theWindowobject is defined. If it is, return theuseLayoutEffect(). Otherwise returnuseEffect().
代码实现
const useIsomorphicEffect =
typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
使用样例
const MyApp = () => {
useIsomorphicEffect(() => {
window.console.log('Hello');
}, []);
return null;
};
ReactDOM.createRoot(document.getElementById('root')).render(
<MyApp />
);
翻译自:https://www.30secondsofcode.org/react/s/use-isomporphic-effect