State Management
Relevant source files
The following files were used as context for generating this wiki page:The medical-calculators application employs a straightforward state management strategy, primarily relying on React's built-in hooks. The architecture favors local component state for individual calculators, ensuring they are self-contained and modular. A global state is used sparingly, specifically for managing the application's language settings through React's Context API.
This approach keeps the complexity low and aligns with the component-based architecture of the Next.js application. The main page controls which calculator is active, while each calculator component is responsible for its own inputs, results, and UI state.
State Management Hierarchy
The application's state is managed at three distinct levels: Global, Application, and Component.
This diagram illustrates the state hierarchy, with the global LanguageContext at the top, followed by the application-level state in page.tsx that controls the active calculator, and finally the local state within each calculator component.
Sources: src/app/layout.tsx:29-31, src/app/page.tsx:11, src/calculators/PediatricDoseCalculator.tsx:11
Global State: Internationalization (i18n)
Global state is exclusively used for managing the application's language for internationalization (i18n). This is implemented using React's Context API.
LanguageContext
The LanguageContext provides the current language and a function to update it to all components wrapped within the LanguageProvider.
-
LanguageContext.tsx: This file defines the context and the provider component.- It creates a context to hold the current language (
language) and the setter function (setLanguage). - The
LanguageProvidercomponent uses auseStatehook to manage thelanguagestate, which defaults to 'ru' (Russian). - The provider wraps its children, making the language state and setter function available throughout the component tree.
- It creates a context to hold the current language (
-
layout.tsx: The root layout wraps the entire application with theLanguageProvider, making the language context globally accessible.
// src/app/layout.tsx:27-33
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className="h-full">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased h-full`}
>
<div className="flex flex-col min-h-full">
<LanguageProvider>
{children}
</LanguageProvider>
</div>
</body>
</html>
);
}
Sources: src/i18n/LanguageContext.tsx, src/app/layout.tsx:27-33
Application-Level State
The main application page, src/app/page.tsx, manages state related to the overall application UI, such as which calculator is currently active.
activeCalculator: A state variable of typeCalculatorTypethat determines which calculator component is rendered. It is initialized to'home'.isMobileMenuOpen: A boolean state that controls the visibility of the mobile navigation menu.
The state is managed using the useState hook. User actions, like clicking a navigation button, call the setActiveCalculator function to update the state and render the corresponding calculator component.
// src/app/page.tsx:11-13
export default function Home() {
const [activeCalculator, setActiveCalculator] = useState<CalculatorType>('home');
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
// ...
}
Sources: src/app/page.tsx:11-13
Component-Level (Local) State
Each calculator is a self-contained component that manages its own state locally using the useState hook. This is the primary method of state management in the application and is the recommended pattern for adding new calculators.
Sources: CONTRIBUTING.md
State Structure in Calculators
A typical calculator component, such as PediatricDoseCalculator or BloodGasAnalysisCalculator, manages several pieces of state:
| State Variable | Type | Purpose | Example File |
|---|---|---|---|
inputs | object | Stores all user-provided data from form fields (e.g., weight, age). | PediatricDoseCalculator.tsx |
result | object | null | Stores the calculated results. It is null initially and populated upon calculation. | PediatricDoseCalculator.tsx |
data | object | A common name for the input state object, seen in more complex calculators. | BloodGasAnalysisCalculator.tsx |
| UI State | boolean or string | Manages UI-specific states like search terms, dropdown visibility, or toggling advanced sections. | PediatricDoseCalculator.tsx |
Sources: src/calculators/PediatricDoseCalculator.tsx:11-20, src/calculators/BloodGasAnalysisCalculator.tsx:109-136
Data Flow within a Calculator Component
The data flow is unidirectional and follows a standard React pattern.
This sequence diagram shows the typical interaction flow within a calculator component.
Sources: src/calculators/PediatricDoseCalculator.tsx:43-294
Example: PediatricDoseCalculator
This calculator demonstrates the standard local state management pattern.
-
State Initialization: The component initializes state for inputs, results, and UI elements.
// src/calculators/PediatricDoseCalculator.tsx:11-20 const [inputs, setInputs] = useState<PediatricDoseInputs>({ age: null, weight: null, height: null, medication: '', indication: '', route: 'oral', }); const [result, setResult] = useState<PediatricDoseResult | null>(null); const [searchTerm, setSearchTerm] = useState(''); -
State Update: An input change triggers a state update.
// src/calculators/PediatricDoseCalculator.tsx:341-344 <NumberInput label={t.childAge} value={inputs.age} onChange={(value) => setInputs({ ...inputs, age: value })} // ... /> -
Calculation and Result: The
calculateDosefunction reads from theinputsstate and, upon completion, updates theresultstate.// src/calculators/PediatricDoseCalculator.tsx:43-47 const calculateDose = () => { // Проверяем, что все необходимые поля заполнены if (inputs.age === null || inputs.weight === null || !inputs.medication) { alert(t.pleaseFillAllFields); return; } // ... calculation logic reads from `inputs` // ... // src/calculators/PediatricDoseCalculator.tsx:296-316 setResult({ isSafe: true, // ... other result properties }); }; -
State Reset: The
resetCalculatorfunction restores all local state variables to their initial values.// src/calculators/PediatricDoseCalculator.tsx:319-331 const resetCalculator = () => { setInputs({ age: null, weight: null, height: null, medication: '', indication: '', route: 'oral', }); setResult(null); setSearchTerm(''); setSelectedCategory('all'); setShowAutocomplete(false); setShowMedicationsList(true); };
Sources: src/calculators/PediatricDoseCalculator.tsx, CONTRIBUTING.md
Summary
The state management in medical-calculators is intentionally simple and effective. It leverages local component state via useState for encapsulating calculator logic and uses React's Context API (useContext) for the single global concern: language selection. This design promotes modularity, making it easy to develop, test, and maintain individual calculators without creating complex interdependencies. The main application page acts as a simple router, using its own local state to control which calculator is visible.