IAP 2024 Day 3 - React Lifecycle and Hooks
How state is managed in React
Component rendering works
- Trigger : First time component is called or State Change
- Render : React rims the js code in component and calls subcomponents
- Commit : React puts returned JSX into HTML DOM to be served to viewer
Component Lifecycle
Mount => State Change => ... => Dismount
The useEffect Hook
React Hooks
Hooks are special functions provided by React to access parts of the component lifecycle.
Example:
useState allows us to control the lifecycle of the component.
useEffect() hook
- Runs after specific variables change
- Can think of as response to state change
- Typically used to synchronize with something external to React
- Commonly used to load external data into state
- Call an API/perform some computation/etc. at specific times
- Syntax: useEffect(function, optional dependency array)
- runs fucntion every time a variable in dependency array changes
useEffect(()=>{
/*
Do something here,
e.g. interacting with an external service
*/
return () => {
/*
Clean up here
e.g. close a connection
*/
}
}, [/* dependencies */])
Conditional Render
condition ? resultIfTrue : resultIfFalse
Rendering an Array of Data
Loop render
- Common pattern: render an array of data in React
- E.g. custom dropdown menu, list of data items from database
- Need a simple way to map data to HTML
Using map() in React
render some data in an array
Comments NOTHING