Skip to content

Latest commit

ย 

History

History
39 lines (24 loc) ยท 1.9 KB

File metadata and controls

39 lines (24 loc) ยท 1.9 KB

๐Ÿš€ Overview

This project is a "from-scratch" simulation of the React State Hook made in JSX. It demonstrates the underlying logic React uses to persist data between re-renders without losing the value of variables.

Core Concepts

Persistent Storage: Uses a global array (stateValues) to keep data alive even after the App function finishes executing.

The Index: Uses a callIndex to ensure that countA always grabs the first item in the array and countB always grabs the second.

Manual Reconciliation: Since im not using the real React engine, i use a renderApp function to manually trigger root.render() whenever a state change occurs.

๐Ÿ› ๏ธ How the Engine Works

  1. The Hook Logic (myUseState) The hook identifies which "slot" it belongs to by capturing the current callIndex and then immediately incrementing it for the next hook.

  2. The Render Cycle To prevent the array from growing infinitely, the callIndex must be reset to 0 at the start of every render. This allows the component to reuse the existing slots in the stateValues array.

  3. Initialization & HMR To handle development environments like Vite, the code includes a "Clean Slate" check. This wipes the global array if the script re-executes, preventing "ghost" data from accumulating.

โš ๏ธ Known Behaviors

Why does the array have 4+ items?
If you see more items than hooks in your console, it is usually due to:

React Strict Mode: React renders components twice in development to find bugs. This will double your callIndex unless the pointer is reset correctly.

Hot Module Replacement (HMR): Saving your file re-runs the script. The global stateValues array persists in the browser memory unless explicitly cleared.

๐Ÿ“‚ File Structure

stateValues: The "Master Record" array.

callIndex: The pointer.

myUseState: The custom hook implementation.

App: The UI component using the state.

renderApp: The trigger that redraws the UI.