4IT580: Docs
4IT580 WebGitLab

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:

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:

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:

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

Resources