useState()
🔄 Understanding useState in Modularjs
useState
is a fundamental hook provided by Modularjs that allows you to create reactive state inside your modular components. It works similarly to React’s useState
and lets you manage data that can change over time, triggering your component to update accordingly.
🧩 What is useState ?
useState
lets you declare a state variable inside your module.It returns an array with two values:
The current state value.
A function to update this state.
When you call the update function, Modularjs re-renders the component with the new state.
⚙️ How to use useState
Here is a simple example showing how to use useState
to create a counter inside your Modularjs component:
Explanation:
const [count, setCount] = useState(0);
Initializescount
with the value0
.setCount(count + 1)
updates the state, causing the component to re-render with the new count.
Here is another simple example showing how to use useState
to create a toggle switch inside your Modularjs component:
Explanation:
const [isOn, setIsOn] = useState(false);
initializes the toggle state asfalse
(OFF).Clicking the button calls
setIsOn(!isOn)
, which flips the boolean value.The UI text updates dynamically to reflect the toggle state
💡 Tips for Using useState
You can declare multiple state variables for different data in your component.
Always use the update function (
setCount
in the example) to change state instead of modifying state variables directly.State updates are asynchronous and batched — be mindful when updating state multiple times.
🔮 What’s Next?
Explore
useEffect
to run side effects based on state changes.Combine
useState
with nested Modularjs components to build rich interactive UIs.
This page gives you the core knowledge to start building reactive modules with Modularjs using useState
!
Last updated