DEV Community

Deva I
Deva I

Posted on

Hooks Scenario Questions

Toggle Button :

1.What type of state should you use?
✓ Boolean (true/false).

2.Why must the input value be stored in useState?
✓ Either false (for "OFF") or true (for "ON"), depending on the desired default.

PROGRAM :

OUTPUT :


Input field value :

1.What happens if you use a normal variable?
✓ Without useState the component won't re-render to show the updated text.

2.What kind of state works best?
✓ If you use a normal variable, the value might update in memory, but the UI will not reflect the change because React doesn't know it needs to re-render.

PROGRAM :

OUTPUT :

Show/Hide text :

1.What kind of state works best?
✓ Boolean

2.Why boolean is suitable here?
✓ It acts as a simple binary switch (flag) to conditionally render the paragraph:{isVisible && <p>Text</p>}.
PROGRAM :

OUTPUT :

Character Counter :

1.How do you track text length?
✓ Use .lengthon the stringe(eg: text.length).

2.Should you store both text and length in state?
✓ No, you should only store the text.
✓The length is "derived state" and can be calculated during render to avoid redundant data.

PROGRAM :

OUTPUT :

Top comments (0)