HYDROXIDE

Lifecycle Functions

Run code when components connect and disconnect

Lifecycle functions let you run code at specific points in a component's lifecycle.

import { reactive, onConnect, onDisconnect } from 'hydroxide';

function Timer() {
  const seconds = reactive(0);
  let interval;

  onConnect(() => {
    console.log('Timer connected');
    interval = setInterval(() => seconds.do(s => s + 1), 1000);
  });

  onDisconnect(() => {
    console.log('Timer disconnected');
    clearInterval(interval);
  });

  return <p class="timer">{seconds()}s</p>;
}

function App() {
  const show = reactive(true);

  return (
    <div class="container">
      <button class="primary-button" on-click={() => show.do(v => !v)}>
        {show() ? 'Stop' : 'Start'} Timer
      </button>
      <Timer if={show()} />
    </div>
  );
}

export default App;

onConnect

Runs once when the component is connected to the DOM:

import { onConnect } from 'hydroxide'

function App() {
  onConnect(() => {
    console.log('Component mounted')
  })

  return <div>Hello</div>
}

Use onConnect for:

  • Initial data fetching
  • Setting up subscriptions
  • DOM measurements

onDisconnect

Runs when the component is removed from the DOM:

import { onDisconnect } from 'hydroxide'

function App() {
  onDisconnect(() => {
    console.log('Component unmounted')
  })

  return <div>Hello</div>
}

Use onDisconnect for:

  • Clearing intervals/timeouts
  • Removing event listeners
  • Cancelling subscriptions

Custom Functions

Combine lifecycle functions with reactives to create reusable functions. Here's a cursor position tracker:

import { reactive, onConnect, onDisconnect } from 'hydroxide';

function getCursorPosition() {
  const position = reactive({ x: 0, y: 0 });

  function handleMouseMove(e) {
    position.set({ x: e.clientX, y: e.clientY });
  }

  onConnect(() => {
    window.addEventListener('mousemove', handleMouseMove);
  });

  onDisconnect(() => {
    window.removeEventListener('mousemove', handleMouseMove);
  });

  return position;
}

function App() {
  const position = getCursorPosition();

  return (
    <div class="container">
      <div class="coords">
        <span class="label">x</span>
        <span class="value">{position().x}</span>
      </div>
      <div class="coords">
        <span class="label">y</span>
        <span class="value">{position().y}</span>
      </div>
    </div>
  );
}

export default App;

On this page