Topics Covered
Slides: slides.com/joelross/info340wi26-react-apps
Development Workflow
- Use Vite dev server to transpile React, manage dependencies, and auto-reload
- Always test in browser before running Jest
- Git workflow: merge starter branch into main for updates
React Components Review
- Components are functions that return JSX elements
- Component names must be capitalized
- Props are input parameters passed via XML-style attributes
- Access props through the
props object parameter
- Props can be strings, arrays, objects, or functions (callbacks)
Component Composition
- Arrays of components render as sibling elements
- Use
.map() to create component collections from data arrays
- Each list item needs a unique
key prop to help React track changes
- Pattern: "passing props down" from parent to child components
State Management with useState()
State tracks internal, changeable data within a component:
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
useState(initialValue) returns an array: [stateVar, setterFunction]
- Naming convention:
[variable, setVariable]
- Calling the setter function triggers a re-render of the component
- State updates are asynchronous — logging state in event handlers won't reflect new values immediately
State vs Props
- Props: Passed from parent, unchanging from the component's perspective
- State: Changes over time, usually through user interaction
- Don't use state if the value can be derived from other state or props
- If data doesn't change, it's a prop. If it changes over time, it's state
Event Handling in React
- React uses special props for events:
onClick, onChange, onSubmit
- Pass a callback function (don't call it):
onClick={handleClick}
- Event listeners attach only to HTML elements, not custom components
- Use
event.preventDefault() for form submissions
Debugging React
- Log state at the rendering level (top of component function), not inside event handlers
- State changes are async, so
console.log inside handlers shows old values
- Use React DevTools to inspect component tree and state