Skip to content

GeorgeCodes88/Custom-UseState-Hook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors