1 of 48

Intro to React

CSCI 344: Advanced Web Technologies

Spring 2025

1

2 of 48

Announcements

  • Tutorial 7 is due Monday (3/24)
  • Homework 3 due on Friday at midnight (3/28)
    1. Please take advantage of the videos if they’re helpful!
  • Quiz 2b: JavaScript II is on Monday, 3/31

2

3 of 48

Outline

  1. Reflection so far
  2. New JavaScript concepts
  3. Example of a React Application
  4. The rules of React

3

4 of 48

Outline

  1. Reflection so far
  2. New JavaScript concepts
  3. Example of a React Application
  4. The rules of React

4

5 of 48

Reflection so far…

  • First: some humor: Gary Burnhardt’s famous JavaScript Wat Video (ffw to minute 1:23).
  • Question for the class: reflect on the code you’ve been writing for HW3:
    • Has it been difficult to organize?
    • Does it feel messy?
    • Does it feel difficult to debug?
    • Your thoughts here…

5

6 of 48

Your thoughts here…

  • ????

6

7 of 48

What problems does React solve (Pros)?

Why would you want to use a client-side framework?

  1. Encourages you to group related HTML, CSS and JavaScript logic into blocks or ‘components’
  2. Standardizes the interfaces and techniques for handling workflow and user interactions
    • Makes it easier for teams to work together
    • Helps to manage complexity as your app gets bigger.
  3. Developer communities emerge – produce open-source components and plugins that can facilitate rapid development.

7

8 of 48

Could it also make things harder (Cons)?

Why would you not want to use a client-side framework?

  1. Steep learning curve
  2. Might be overkill for what you need
    • Sometimes all you need is a light-weight JS function to do the job!
  3. Example: React is only useful if:
    • You’re making a bunch of server requests from a single-page application
    • You’ve got a lot of client-side components that you need to manage

8

9 of 48

Review of JavaScript So Far

Over the past two weeks, we’ve discussed some new JavaScript ideas:

  1. “Higher Order” array methods such as map, filter, forEach, and reduce, that accept a function as an argument. The “argument function” is then invoked on every item in the array.
  2. Using template literals (backtick character) to create longer, more complex HTML snippets (that can be dynamically added to the DOM)
  3. The fetch function, which allows JavaScript to interact with other servers using HTTP.
  4. async / await: Used if you need to wait for an asynchronous promise to resolve.

9

These ideas are important, so make sure you review and understand them!

10 of 48

New JavaScript Concepts

In addition to the concepts we’ve discussed, there are a few other programming / JavaScript ideas that React leverages that are important to understand. Namely:

  1. Functional programming philosophy
  2. ES6 Modules
  3. Closures

10

11 of 48

1. Functional Programming v. OOP

  • A programming paradigm that relies on “pure functions” as much as possible
  • A pure function is one whose results are dependent only upon the input parameters, and whose operation initiates no side effect, that is, makes no external impact besides the return value.
  • Makes heavy use of immutability:
    • No variables are updated after they are assigned (makes code easier to reason about)
  • Functions are often passed in as data, and functions are also returned from functions.

11

12 of 48

2. ES6 Modules

  • Modules allow you to separate logical groupings of functionality, and given them a private scope (versus having everything on the global scope).
  • You can create public variables, functions, and objects using the “export” keyword. If you don’t use the “export” keyword, than the item is private.
  • You can also import modules and access them in other JavaScript files.
  • In HW3, main.js is a module, which is why we had to put our event handlers on the window scope.

12

13 of 48

3. Closures

A closure gives you access to an outer function's scope from an inner function (see example). Used to encapsulate variable scope

13

function init() {

let name = "Walter"; // name is a local variable created by init

// inner function, that forms the closure

function displayName() {

console.log(name); // use variable declared in the parent function

}

displayName();

}

init(); // prints Walter

console.log(name); // throws an error

14 of 48

4. Object Destructuring

Object destructuring is just a shortcut for extracting object properties and assigning them to variables. Take a look at this example:

const person = {

name: 'Alice',

age: 25,

city: 'Wonderland'

};

// Destructuring with curly braces

const { name, age } = person;

console.log(name); // Output: 'Alice'

console.log(age); // Output: 25

14

15 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

15

16 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

16

17 of 48

Most Important: Do the readings

Please complete the readings. It will take you a few hours, but you won’t be able to make progress with React without understanding some of the core React conventions and workflow, including:

  • (Required) Describing the UI
  • (Recommended) Tic Tac Toe

17

18 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

18

19 of 48

Let’s start with a concrete example

Follow along with this activity!

You will complete steps 1-4 (for now).

19

20 of 48

Discuss the Setup Process

  1. Installing dependencies
  2. What is vite doing (npm run dev)?
  3. What is a bundler?
  4. If React isn’t valid JavaScript, then how does the browser understand it?

20

21 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

21

22 of 48

JSX

  1. A syntax extension to JavaScript; works similarly to a template literal
  2. Philosophy: Putting HTML & JS into the same file – via “components” – is easier to reason about. Keeping them separate is confusing.
  3. JSX not required, but suggested when using React. Example:

22

23 of 48

JSX Syntax

Some syntax things...

  1. camelCase convention for properties and variable names (just like JavaScript)
  2. No quotes around the JSX itself
  3. Quotes around constants
  4. Curly braces instead of quotes around JavaScript expressions
  5. Use className (instead of class) to assign CSS classes

23

<img className="thumbnail" src={post.image_url} />

24 of 48

JSX Example

<div className="post">

<h2>{post.user.username}</h2>

<img className="pic" src={post.image_url} />

<p>{post.last_updated}</p>

</div>

24

25 of 48

Useful Tool: HTML to JSX Converter

https://transform.tools/html-to-jsx

25

26 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

26

27 of 48

React Components

  1. Allow you split the UI into independent, reusable pieces, and think about each piece in isolation (all JS frameworks do this, btw).
  2. A special kind of JavaScript function that:
    1. Accepts arbitrary inputs (called “props”)
    2. Returns a React element (JSX)
  3. All components must start with a capital letter (a naming convention that is enforced)
  4. Props – which are passed into the component – are read-only (immutable)

27

28 of 48

Component Rules

  1. Components accept an optional “props” object (optional)
  2. Components must return a JSX element

28

export function Welcome({name}) {�

// all components return JSX (a UI widget)

return <h1>Hello, {name}</h1>;

}

29 of 48

Using Components

Once you create a component function / class, you can use it like regular HTML syntax (so long as you import the component). Pretend you’re looking at the App.jsx file below:

// first import your component:

import Welcome from './Welcome';

export default function App(props) {

// You can use your component like a regular tag:

return <Welcome name="Sarah" />

}

29

30 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

30

31 of 48

Handling Events

Let’s just look at the documentation and talk about it...

<button role="switch"

className="like"

aria-checked="false"

onClick={toggleLike}>

Like

</button>

31

32 of 48

Overview of React

  1. Do the readings
  2. Example
  3. Intro to JSX
  4. Components
  5. Event Handlers
  6. State management
  7. Effects

32

33 of 48

State and Lifecycle

  1. state variables must be declared for any variables whose changes to them might require a screen redraw
  2. All state variable changes trigger a request for the corresponding component to “redraw itself.” Examples of where you might want to use state:
    • A user likes or bookmarks a post
    • A user adds a new comment to the post
  3. When any of these interactions happens, you will update the component’s state…which will force a redraw.

33

34 of 48

Update State using the built-in useState() function

import { useState } from 'react';

function Carousel() {

const [index, setIndex] = useState(0); // pass in initial value

}

  • useState taks an initial value as an argument
  • Returns a list with two values: the current state and a setter function
  • See documentation: https://beta.reactjs.org/reference/react/useState

34

35 of 48

“State” Takeaways

  1. If you update a component’s state, this will automatically trigger a component redraw (for the associated component).
  2. Take advantage of this fact when designing your UI. For instance:
    1. User clicks the heart to like a post
    2. Click event issues a POST request to /api/posts/<id>/likes
    3. If the request is successful, a GET request is issued to /api/posts/<id> to get an updated Post object.
    4. If the request is successful, modify the state to store the updated post.
    5. The updated state automatically redraws the post (which in turn redraws all of the child components).

35

36 of 48

“Lifting Up” State

  1. The state of a component is only accessible to the component (it’s encapsulated)!
  2. If you want a state change to “notify” another component (i.e. “lifting up the state”), then your child component needs to be granted access to a function that belongs to the parent of the component (passed to the child as a property)

For example, if your “add new comment” functionality would like to notify a parent component to requery and redraw the post, then the requeryPost() functionality needs to be defined in the parent and then passed down to the the child component (as a property).

36

37 of 48

Overview of React

  1. Do the readings
  2. Intro to JSX
  3. Components
  4. Event Handlers
  5. State management
  6. Effects

37

38 of 48

But how do you request Server data using React?

Recall:

  • React Components are intended to be “pure” (i.e. they can only access data that are passed into them via props)
  • If you want React to “reach outside” of its sandbox, you have to do it in a very particular way in order for React to behave correctly.
  • Specifically, if you want to interact with external system (i.e. via fetch requests, web sockets, etc.) you can either use an event handler or a useEffect() hook (Effect → think “side effects”).

38

39 of 48

Effects and the useEffect() hook

Effects are an escape hatch from the React paradigm. They let you “step outside” of React and synchronize your components with some external system like a non-React widget, network, or the browser DOM.

Examples:

  • I want to fetch (POST, GET, DELETE, PATCH, PUT) some data from a server when the component first loads.
  • I want to respond to a message that was just received from a chat server (via websocket)
  • I want to coordinate with a JS widget outside of react (e.g. Google Maps, the browser’s built-in audio / video / canvas API)

39

40 of 48

How to write an Effect

To write an Effect, follow these three steps:

  1. Declare an Effect. By default, your Effect will run after every render (which you most often DO NOT WANT).
  2. Specify the Effect dependencies. Most Effects should only re-run when needed rather than after every render. For example, connecting and disconnecting to a chat room should only happen when the component appears and disappears, or when the chat room changes. You will learn how to control this by specifying dependencies.
  3. Add cleanup if needed. Not relevant for PhotoApp, but definitely relevant for a chat app.

40

41 of 48

1. Declare an Effect

import { useEffect } from 'react';

function MyComponent() {

useEffect(() => {

// Code here will run after *every* render

});

return <div />;

}

CAVEAT: Because the useEffect function is run after every render, it can easily produce an infinite loop. To avoid, see next slide.

41

42 of 48

2. Specify the Effect dependencies

Use dependencies to control when the useEffect function is invoked:

To only run it once (on initialization), pass in an empty array:

useEffect(() => {

// ...

}, []);

To run it when one or more properties change, pass in the relevant properties:

useEffect(() => {

// ...

}, [prop1, prop2]);

42

43 of 48

Relevant Readings

43

44 of 48

Summary of Key Ideas in React

44

Components

Components are encapsulated units of logic that help you organize your code.

  • They can only access data that are passed in via props.
  • They return a JSX element

JSX

JSX is React’s version of HTML (see previous slides for syntax rules)

Props

Props (properties) are read-only data fields that are passed into a component from its parent.

State

  • State variables are used when a change to a component’s data ought to trigger a redraw.
  • Use the useState function to generate the variable and a setter function
  • Every change to a state variable causes the component (and all of its child components) to redraw.

Effects

  • To interact with systems / APIs that exists outside of the “pure” Component
  • Use the useEffect function hook to issue external logic
  • useEffect hook runs on every render unless dependencies are specified

45 of 48

Preview of Tutorial 8 & Homework 4

45

46 of 48

Preview of Tutorial 8 & Homework 4

Phase 1

  1. Draw boxes around the components
  2. Create a static version of everything

Phase 2

  1. Figure out which aspects of the component (if any) will change based on a user interaction
  2. Decide where your state should live
  3. Figure out how to pass data to child components (via props)

46

47 of 48

What are the

components?

47

48 of 48

What are the

components?

48