DOCUMENTATION: FluxState API Reference: Temporal Hooks

3 min read
Managing time-traveling state with bi-directional reactivity in FluxState 3.0

Overview

Temporal Hooks allow components to observe, modify, and react to state changes across multiple timelines. Unlike traditional state management where state flows forward, FluxState enables bi-directional state propagation with automatic paradox resolution.

Package: @fluxstate/temporal
Version: 3.0.0+
Status: Stable (Experimental features marked with ⚠️)

Basic Concepts

Timeline

A Timeline represents a single causality chain of state mutations. Components can exist on multiple timelines simultaneously.

interface Timeline {
  id: string;
  branch: number;
  parent?: Timeline;
  children: Timeline[];
  state: StateSnapshot;
}

Temporal Context

Every FluxState component operates within a TemporalContext that determines its visibility across timelines.

const ctx = new TemporalContext({
  mode: 'parallel', // 'linear' | 'parallel' | 'quantum'
  maxBranches: 5,
  collapseStrategy: 'most-probable' // 'most-probable' | 'first-observed' | 'manual'
});

Core Hooks

useTemporalState

Creates state that persists across timeline branches.

const [value, setValue, timeline] = useTemporalState(initialValue, options);

Parameters:

  • initialValue: Initial state value
  • options: Configuration object
Option Type Default Description
persistent boolean true Survives timeline collapses
branching string 'auto' When to create branches
paradoxHandler function null Custom paradox resolution

Example:

function Counter() {
  const [count, setCount, timeline] = useTemporalState(0, {
    branching: 'on-mutation',
    paradoxHandler: (conflicts) => Math.max(...conflicts)
  });

  const handleIncrement = () => {
    setCount(count + 1);
    // Creates new timeline branch
  };

  return (
    <div>
      Count: {count}
      Timeline: {timeline.id}
      Branches: {timeline.children.length}
    </div>
  );
}

usePastState

Observes state from previous timeline positions.

const pastValues = usePastState(stateRef, depth);

Parameters:

  • stateRef: Reference to temporal state
  • depth: How many steps back (default: 1)

Returns: Array of past values in reverse chronological order

⚠️
Warning: Accessing past state beyond branch points may trigger cascade recalculation.

useFutureState

Predictively computes probable future states.

const [predictions, confidence] = useFutureState(stateRef, options);

Parameters:

  • stateRef: Reference to temporal state
  • options.steps: Steps into future (max: 10)
  • options.algorithm: 'markov' | 'neural' | 'deterministic'

Example:

function PredictiveInput() {
  const [text, setText] = useTemporalState('');
  const [predictions, confidence] = useFutureState(text, {
    steps: 3,
    algorithm: 'neural'
  });

  return (
    <div>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      {confidence > 0.7 && (
        <div>Likely next: {predictions[0]}</div>
      )}
    </div>
  );
}

Advanced Patterns

Paradox Resolution

When timeline branches reconverge, conflicts must be resolved.

const paradoxResolver = new ParadoxResolver({
  strategy: 'weighted-merge',
  weights: {
    userInitiated: 1.0,
    automated: 0.5,
    predicted: 0.3
  }
});

useTemporalState(initialValue, {
  paradoxHandler: paradoxResolver.resolve
});

Timeline Synchronization

Synchronize state across multiple component timelines.

function SyncedComponents() {
  const sync = useTimelineSync(['component-a', 'component-b']);
  
  useEffect(() => {
    sync.on('divergence', (delta) => {
      console.warn(`Timelines diverged by ${delta}ms`);
    });
  }, [sync]);

  return <div>{/* components */}</div>;
}

Temporal Middleware

Intercept and modify state changes across all timelines.

const timeLogger = (timeline, mutation) => {
  console.log(`[${timeline.id}] ${mutation.type}: ${mutation.payload}`);
  return mutation; // or modified mutation
};

FluxState.use(timeLogger);

Performance Considerations

Memory Management

Each timeline branch maintains a complete state snapshot. Use collapseTimelines() to merge resolved branches.

// Automatic cleanup
useEffect(() => {
  const interval = setInterval(() => {
    FluxState.collapseTimelines({
      olderThan: 5000, // 5 seconds
      keepActive: true
    });
  }, 10000);
  
  return () => clearInterval(interval);
}, []);

Optimization Flags

FluxState.configure({
  enableQuantumMode: false, // Reduces CPU usage by 40%
  maxTimelineDepth: 100,    // Prevents memory leaks
  lazyBranching: true,      // Creates branches only when accessed
  useWebWorkers: true       // Offload calculations
});

Error Handling

Common Errors

Error Cause Solution
TimelineOverflow Too many branches Increase maxBranches or enable pruning
ParadoxException Unresolvable conflict Implement custom paradoxHandler
TemporalLeak State escaping context Wrap in TemporalBoundary
CausalityLoop Circular dependency Use breakLoop() directive

Debugging

Enable temporal debugging in development:

if (process.env.NODE_ENV === 'development') {
  FluxState.debug({
    logTimelines: true,
    visualizeGraph: true,
    paradoxBreakpoints: true
  });
}

Migration Guide

From FluxState 2.x

// Old (2.x)
const [state, setState] = useState(initial);

// New (3.0)
const [state, setState, timeline] = useTemporalState(initial);
// Third parameter is optional for backward compatibility

From Redux-Temporal

// Redux-Temporal
dispatch(timeTravel(-1));

// FluxState 3.0
const past = usePastState(stateRef, 1);
// Automatic, no manual dispatch needed

Best Practices

  1. Limit branch depth: Deep timelines impact performance
  2. Use deterministic IDs: Helps with debugging and testing
  3. Implement paradox handlers: Don't rely on defaults
  4. Test with TemporalTestUtils: Ensures timeline consistency
  5. Monitor memory usage: Timelines can grow exponentially

⚠️ Experimental Features

  • Quantum Superposition: State exists in multiple values simultaneously
  • Retroactive Computation: Modify past computations without cascading
  • Timeline Sharding: Distribute timelines across workers
  • Neural Prediction: ML-based future state prediction

Support

GitHub Issues: github.com/fluxstate/core/issues
Discord: discord.gg/fluxstate
Stack Overflow: Tag with fluxstate and temporal-hooks

Natan Nikolic
Natan Nikolic — Freelance product designer based in London. Before founding about:blank studio, he was VP of Product at Celtra, and helped entrepreneurs build startups 0-1.