Server-side usage
EffCSS
allows to use styles on the server side. You can use it for SSR or SSG since Style Consumer
serialize initial settings for Style provider
.
Style consumer is self-sufficient
It's very simple - Style consumer
himself will understand that he is not in the browser and will emulate the work of Style provider
. Just stringify and add to HTML <head></head>
it when your layout is ready.
Here is React SSR example.
ts
import { StrictMode } from 'react';
import { renderToString } from 'react-dom/server';
import App from './App';
import { StyleProvider } from './styleContext.tsx';
import { createConsumer } from 'effcss/consumer';
export function render(_url: string) {
// emulates Style provider methods and stores stylesheet makers
const consumer = createConsumer({ hydrate: true });
const html = renderToString(
<StrictMode>
<StyleProvider consumer={consumer}>
<App />
</StyleProvider>
</StrictMode>
);
// consumer.toString returns HTML string with initial Style provider state
const head = '' + consumer;
return { html, head };
}
ts
import { StrictMode } from 'react';
import { hydrateRoot } from 'react-dom/client';
import App from './App';
import { StyleProvider } from './styleContext.tsx';
import { createConsumer } from 'effcss/consumer';
const consumer = createConsumer();
hydrateRoot(
document.getElementById('root'),
<StrictMode>
<StyleProvider consumer={consumer}>
<App />
</StyleProvider>
</StrictMode>
);