2nd Practical Class:
React State, Props & Hooks
In the previous lecture, we learned how to work with primitives and simple props. Now we’ll extend that knowledge to TypeScript props, managing arrays and objects in state, and encapsulating logic inside custom hooks.
Props & TypeScript
Props = inputs to a component.
They are read-only, passed from parent → child. 👉 In TypeScript, we explicitly declare props with a or .
Defining Props
Optional Props
Default Values
Extending Native Element Props
✅ This way our component:
- accepts all native button props (onClick, disabled, etc.)
- plus our own custom prop .
State with Arrays and Objects
Previously we worked with primitive state. Now let’s manage arrays and objects immutably.
Adding to an Array
Updating an Object in an Array
Removing from an Array
Keys in Lists
When rendering lists with , React requires a prop:
- The must be unique and stable (IDs are best).
- React uses it to know which items changed, added, or removed.
- Without keys, React may reuse the wrong DOM nodes → causing subtle UI bugs.
Custom Hooks
A custom hook is a function that uses other hooks. It allows us to extract business logic out of a component, so the component only focuses on markup and consuming the hook’s API.
✅ Benefits of custom hooks:
- Encapsulation: logic is separated from UI.
- Reusability: same hook can be used across many components.
- Clarity: components become responsible only for rendering, not business rules.
Lifting State Up
Sometimes two (or more) components need to share the same state. Instead of duplicating state in both, we move the state up into their closest common parent and pass it down as props.
✅ The state () lives in the parent. Both child components stay simple and just receive props.
Recap
-
In TypeScript, always define prop types:
- for optional props
- destructuring for default values
- to extend native elements
-
State with arrays/objects must be updated immutably
- use spread to add
- use to update
- use to remove
-
Always use the callback form if new state depends on old
-
Always provide a unique when rendering lists
-
Use custom hooks to encapsulate logic → components stay clean and focused on markup
-
Lift state up when multiple components need to share the same data