CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mobx-react-lite

Lightweight React bindings for MobX based on React 16.8+ and Hooks

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

static-rendering.mddocs/

Static Rendering Support

Server-side rendering utilities that control reactive behavior in SSR environments. These APIs ensure components render correctly on the server without creating MobX reactions or memory leaks.

Capabilities

enableStaticRendering Function

Enables or disables static rendering mode for server-side rendering environments. When enabled, observer components will not create MobX reactions and will render only once.

/**
 * Enables or disables static rendering mode for SSR environments
 * @param enable - True to enable static rendering, false to disable
 */
function enableStaticRendering(enable: boolean): void;

Usage Examples:

import { enableStaticRendering } from "mobx-react-lite";

// Enable static rendering on the server
if (typeof window === "undefined") {
  enableStaticRendering(true);
}

// In Next.js _app.tsx or similar SSR setup
import { enableStaticRendering } from "mobx-react-lite";

// Enable static rendering for server-side rendering
enableStaticRendering(typeof window === "undefined");

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

// In a Node.js server rendering setup
import { renderToString } from "react-dom/server";
import { enableStaticRendering } from "mobx-react-lite";

// Enable before server rendering
enableStaticRendering(true);

const html = renderToString(<App />);

// Optionally disable after rendering if reusing the same process
enableStaticRendering(false);

isUsingStaticRendering Function

Returns whether static rendering mode is currently enabled. Useful for debugging or conditional logic based on rendering environment.

/**
 * Returns the current static rendering mode status
 * @returns True if static rendering is enabled, false otherwise
 */
function isUsingStaticRendering(): boolean;

Usage Examples:

import { isUsingStaticRendering } from "mobx-react-lite";

// Conditional behavior based on rendering mode
const MyComponent = observer(() => {
  const store = useStore();
  
  // Only set up subscriptions on the client
  useEffect(() => {
    if (!isUsingStaticRendering()) {
      const subscription = subscribeToUpdates(store);
      return () => subscription.unsubscribe();
    }
  }, [store]);

  return <div>{store.data}</div>;
});

// Debug logging
console.log("Static rendering enabled:", isUsingStaticRendering());

// Conditional API calls
const DataComponent = observer(() => {
  const store = useLocalObservable(() => ({
    data: null,
    loading: false,
    
    async loadData() {
      if (isUsingStaticRendering()) {
        // Skip async operations during SSR
        return;
      }
      
      this.loading = true;
      try {
        this.data = await fetchData();
      } finally {
        this.loading = false;
      }
    }
  }));

  useEffect(() => {
    store.loadData();
  }, [store]);

  return (
    <div>
      {store.loading ? "Loading..." : store.data}
    </div>
  );
});

useStaticRendering Function (Deprecated)

Deprecated wrapper around enableStaticRendering. Use enableStaticRendering instead.

/**
 * @deprecated Use enableStaticRendering instead
 * Enables or disables static rendering mode
 * @param enable - True to enable static rendering, false to disable
 */
function useStaticRendering(enable: boolean): void;

Important Notes

SSR Behavior

When static rendering is enabled:

  • No reactions: Observer components don't create MobX reactions
  • Single render: Components render exactly once without re-rendering on observable changes
  • Memory efficiency: No memory leaks from reactions that would never be cleaned up on server
  • Synchronous rendering: All rendering is synchronous, no async observable updates
  • Cleanup automatic: No manual cleanup required since no reactions are created

Common SSR Patterns

// Typical SSR setup pattern
import { enableStaticRendering } from "mobx-react-lite";

// Enable static rendering for server-side
if (typeof window === "undefined") {
  enableStaticRendering(true);
}

// Universal component that works on both server and client
const UniversalComponent = observer(() => {
  const store = useLocalObservable(() => ({
    data: getInitialData(), // Should be synchronous for SSR
    hydrated: false,
    
    hydrate() {
      if (!isUsingStaticRendering()) {
        this.hydrated = true;
        // Perform client-side initialization
      }
    }
  }));

  useEffect(() => {
    store.hydrate();
  }, [store]);

  return (
    <div>
      <div>Data: {store.data}</div>
      {store.hydrated && <div>Client-side content</div>}
    </div>
  );
});

Integration with SSR Frameworks

Next.js:

// pages/_app.tsx
import { enableStaticRendering } from "mobx-react-lite";

enableStaticRendering(typeof window === "undefined");

Gatsby:

// gatsby-ssr.js
import { enableStaticRendering } from "mobx-react-lite";

export const onRenderBody = () => {
  enableStaticRendering(true);
};

Custom Server:

import express from "express";
import { renderToString } from "react-dom/server";
import { enableStaticRendering } from "mobx-react-lite";

const app = express();

app.get("*", (req, res) => {
  enableStaticRendering(true);
  
  const html = renderToString(<App />);
  
  res.send(`
    <!DOCTYPE html>
    <html>
      <body>
        <div id="root">${html}</div>
        <script src="/bundle.js"></script>
      </body>
    </html>
  `);
});

Performance Considerations

  • Server performance: Static rendering eliminates the overhead of creating and managing MobX reactions on the server
  • Hydration: Components will start creating reactions after hydration on the client
  • Memory usage: Significantly reduces server memory usage by avoiding reaction creation
  • Rendering speed: Faster server rendering since no observable dependency tracking occurs

docs

advanced.md

index.md

local-state.md

observers.md

static-rendering.md

tile.json