The .reset()
Method: Going Back to the Beginning
What is .reset()
?
The .reset()
method is like a "time machine" for your Signify state. It takes your state back to exactly how it was when you first created it. Think of it as an "undo all changes" button.
const sCounter = signify(0); // Initial value is 0
sCounter.set(100); // Now it's 100
console.log(counter.value); // 100
sCounter.reset(); // Back to the beginning!
console.log(counter.value); // 0 (initial value)
Your First Reset Example
Let's start with something simple:
import { signify } from "react-signify";
// Create a simple counter starting at 0
const sCounter = signify(0);
function CounterApp() {
const count = sCounter.use();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => sCounter.set(count + 1)}>Add 1</button>
<button onClick={() => sCounter.reset()}>Reset to 0</button>
</div>
);
}
What happens when you click "Reset to 0"?
- The counter goes back to 0 (its initial value)
- The component automatically re-renders to show 0
- Any other components using this counter also update
Working with Objects
Reset works perfectly with objects too:
const sUserProfile = signify({
name: "John Doe",
email: "john@example.com",
age: 25,
});
function ProfileEditor() {
const profile = sUserProfile.use();
const handleNameChange = (newName) => {
sUserProfile.set((prev) => {
prev.value.name = newName;
});
};
const handleReset = () => {
sUserProfile.reset(); // Back to John Doe, john@example.com, age 25
};
return (
<div>
<input
value={profile.name}
onChange={(e) => handleNameChange(e.target.value)}
placeholder="Name"
/>
<p>Email: {profile.email}</p>
<p>Age: {profile.age}</p>
<button onClick={handleReset}>Reset Profile</button>
</div>
);
}
Why Use Reset?
1. Form Cleanup 🧹
Perfect for clearing forms after submission:
const sFormData = signify({
name: "",
email: "",
message: "",
});
function ContactForm() {
const form = sFormData.use();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await sendEmail(form);
sFormData.reset(); // Clear form after success
alert("Email sent!");
} catch (error) {
alert("Failed to send email");
}
};
return (
<form onSubmit={handleSubmit}>
<input
value={form.name}
onChange={(e) =>
sFormData.set((prev) => {
prev.value.name = e.target.value;
})
}
placeholder="Your name"
/>
{/* Other form fields... */}
<button type="submit">Send</button>
<button type="button" onClick={() => sFormData.reset()}>
Clear Form
</button>
</form>
);
}
2. Component Cleanup 🔄
Prevent memory leaks and data confusion:
const sLocalState = signify({
searchQuery: "",
selectedItems: [],
filters: {},
});
function DataTable() {
const state = localState.use();
// Clean up when component unmounts
useEffect(() => {
return () => {
localState.reset(); // Clean slate for next time
};
}, []);
return <div>{/* Your table content */}</div>;
}
3. Game State Reset 🎮
Perfect for "New Game" functionality:
const sGameState = signify({
score: 0,
level: 1,
lives: 3,
isGameOver: false,
});
function GameUI() {
const game = gameState.use();
const startNewGame = () => {
gameState.reset(); // Everything back to starting values
};
if (game.isGameOver) {
return (
<div>
<h2>Game Over!</h2>
<p>Final Score: {game.score}</p>
<button onClick={startNewGame}>Play Again</button>
</div>
);
}
return (
<div>
<p>Score: {game.score}</p>
<p>Level: {game.level}</p>
<p>Lives: {game.lives}</p>
</div>
);
}
Arrays and Complex Data
Reset handles arrays and nested objects perfectly:
const sTodoList = signify([
{ id: 1, text: "Learn React", done: false },
{ id: 2, text: "Learn Signify", done: false },
]);
function TodoApp() {
const todos = todoList.use();
const addTodo = (text) => {
todoList.set((prev) => {
prev.value.push({
id: Date.now(),
text,
done: false,
});
});
};
const resetTodos = () => {
todoList.reset(); // Back to the original 2 todos
};
return (
<div>
<h3>Todos ({todos.length})</h3>
{todos.map((todo) => (
<div key={todo.id}>
{todo.text} {todo.done ? "✅" : "⏳"}
</div>
))}
<button onClick={() => addTodo("New task")}>Add Todo</button>
<button onClick={resetTodos}>Reset to Original</button>
</div>
);
}
Smart Reset Patterns
Confirm Before Reset
For important data, always ask first:
const sImportantData = signify({
userSettings: { theme: "dark", language: "en" },
documents: [],
preferences: {},
});
function SettingsPanel() {
const data = importantData.use();
const handleReset = () => {
const confirmed = window.confirm(
"Reset all settings to defaults? This cannot be undone."
);
if (confirmed) {
importantData.reset();
}
};
return (
<div>
{/* Settings UI */}
<button onClick={handleReset} className="danger">
Reset All Settings
</button>
</div>
);
}
Partial Reset
Sometimes you want to reset only part of your data:
const sAppState = signify({
user: { name: "John", email: "john@test.com" },
preferences: { theme: "dark", notifications: true },
temporaryData: { searchQuery: "", filters: {} },
});
// Reset only temporary data, keep user and preferences
const resetTemporaryData = () => {
appState.set((prev) => {
prev.value.temporaryData = {
searchQuery: "",
filters: {},
};
});
};
// Full reset except preferences
const resetUserSession = () => {
const savedPreferences = appState.value.preferences;
appState.reset(); // Reset everything to initial state
appState.set((prev) => {
prev.value.preferences = savedPreferences; // Restore preferences
});
};
Multiple State Reset
Reset several related states at once:
const sFormData = signify({ name: "", email: "" });
const sFormErrors = signify({});
const sFormLoading = signify(false);
// Helper function to reset all form states
const resetAllFormStates = () => {
sFormData.reset();
sFormErrors.reset();
sFormLoading.reset();
};
function CompleteForm() {
return (
<form>
{/* Form content */}
<button type="button" onClick={resetAllFormStates}>
Reset Everything
</button>
</form>
);
}
Testing with Reset
Reset is super helpful in tests:
describe("Counter Component", () => {
// Start each test with a clean slate
beforeEach(() => {
sCounter.reset();
});
it("should increment from 0", () => {
expect(counter.value).toBe(0);
sCounter.set(1);
expect(counter.value).toBe(1);
});
it("should reset to initial value", () => {
sCounter.set(100);
sCounter.reset();
expect(counter.value).toBe(0);
});
});
Common Mistakes to Avoid
❌ Don't Reset Global Settings
// Bad: This will confuse users
const sAppTheme = signify("dark");
const handleLogout = () => {
sAppTheme.reset(); // User loses their theme preference!
};
❌ Don't Reset Without User Knowledge
// Bad: User doesn't expect this
const shoppingCart = signify([]);
const handlePageChange = () => {
shoppingCart.reset(); // Cart items disappear unexpectedly!
};
❌ Don't Reset in Render Loops
// Bad: This creates infinite re-renders
function BadComponent() {
const data = someSignify.use();
if (data.length === 0) {
someSignify.reset(); // This happens every render!
}
return <div>Content</div>;
}
Best Practices ✅
1. Reset Local State
Perfect for component-specific data that should be cleaned up.
2. Preserve User Preferences
Don't reset things like themes, languages, or settings.
3. Confirm Important Resets
Always ask before resetting valuable user data.
4. Use in Cleanup
Reset in useEffect
cleanup to prevent memory leaks.
5. Reset in Tests
Start each test with a known state.
When to Use Reset vs Manual Update
Scenario | Use Reset | Use Manual Update |
---|---|---|
Clear form after submit | ✅ Reset | ❌ Manual |
Component cleanup | ✅ Reset | ❌ Manual |
Partial data clearing | ❌ Reset | ✅ Manual |
Keep some values | ❌ Reset | ✅ Manual |
Test setup | ✅ Reset | ❌ Manual |
Performance Notes
- Reset is fast: It just swaps references, no heavy operations
- Automatic notifications: All components update automatically
- Memory efficient: Old data gets garbage collected
TypeScript Support
Reset works perfectly with TypeScript:
interface UserProfile {
name: string;
email: string;
preferences: {
theme: "light" | "dark";
notifications: boolean;
};
}
const userProfile = signify<UserProfile>({
name: "",
email: "",
preferences: {
theme: "light",
notifications: true,
},
});
// TypeScript knows the exact shape after reset
sUserProfile.reset();
const profile: UserProfile = userProfile.value; // ✅ Type-safe
Summary
The .reset()
method is your "back to the beginning" button. It's perfect for:
- 🧹 Cleaning forms after submission
- 🔄 Component cleanup to prevent memory leaks
- 🎮 Game resets and starting over
- 🧪 Test setup for consistent starting points
- 🚨 Error recovery when data gets corrupted
Remember: Only reset data that users expect to lose. Keep their preferences, settings, and important choices safe!
💡 Quick Tip: Think of reset as "restore factory settings" for your state. Use it when you want a completely fresh start!