Core Concepts of the Project

Necessary Concepts for Random Joke Generator

This module focuses on essential React concepts you'll use while building the app. You'll explore components, functions, hooks like useState, and how to fetch data from external APIs like JokeAPI, all in a practical and beginner-friendly way.

Components

Components are the building blocks of a React app. A component can be thought of as a function (or class) that returns some part of the UI.

We typically create one main App component and other smaller components (like Joke and Button) that can be reused.

For example, our Joke component handles fetching and displaying the joke, while a Button component renders the button element. Components accept inputs called props and render UI accordingly.

Functions (Arrow Functions & Event Handling)

React code often uses arrow functions and event handlers. For instance, we define a function like fetchJoke = () => { ... } inside a component to fetch data.

Event handlers (e.g., onClick) are passed these functions to respond to user actions. In our app, we attach an onClick event to the button that calls a function to fetch a joke. These functions keep our code organized and link UI events to logic.

State & Hooks

In React function components, state is used to store data that changes over time. We use the useState Hook to add state to our component. For example, const [joke, setJoke] = useState("") creates a state variable joke initialized to an empty string.

The React documentation notes that “useState is a React Hook that lets you add a state variable to your component.”. Whenever we update this state (via setJoke), React re-renders the component to show the new value. This is how the fetched joke text appears in the UI after the button is clicked.

Fetching Data from an API

Our app fetches jokes from the JokeAPI using the browser’s fetch function. A typical fetch call looks like:

fetch("https://sv443.net/jokeapi/v2/joke/Any?type=single")

.then(res => res.json())

.then(data => setJoke(data.joke));

This sends an HTTP GET request to the API. When the JSON response arrives, we extract the joke text and update the joke state. (See a similar example of fetching from the JokeAPI.) This asynchronous API call happens inside our fetchJoke function and ensures the UI shows the latest joke.