Skip to content

Chapter 4

Nov. 1

Chapter 4 summary

04_01 Generating a project with Create React App

  • Create React App helps set up and manage React projects.
  • Ensure Node.js is installed on your system, and if not, download and install it from nodejs.org.
  • Confirm Node.js and npm are installed by running node -v and npm -v in your terminal.
  • Use the command npx create-react-app project-name to create a new React project. Replace “project-name” with your desired project name.
  • This command sets up a React project with essential dependencies, including React, ReactDOM, and react-scripts for building and bundling.
  • Navigate to the project folder using cd project-name.
  • Start the development server with npm start, which will open a browser window displaying your React app running on localhost:3000.

04_02 Touring a Create React App project

  • The project is generated in a folder, typically named after your project (e.g., “react-app”).
  • Key dependencies in the package.json file include React, ReactDOM, and React Scripts.
  • The src folder contains essential files for your app, including index.js, which serves as the entry point for rendering your app.
  • index.js uses ReactDOM.render() to inject your React app into an HTML element with the ID “root” in the public/index.html file.
  • In the src folder, you’ll find your main App.js component file, where your React components are created and exported.
  • The app component is wrapped in a React.StrictMode component for enhanced development error checking.
  • You can use CSS files for styling your components, which can be imported and applied to your components.
  • Running npm start starts a development server and automatically reloads your app in the browser as you make changes, making development easier and faster.

04_03 Destructuring arrays and objects

Destructuring in JavaScript is a key concept that helps in handling properties and values efficiently. It is particularly useful when working with React components and state management. Here are the main takeaways:

  • Destructuring allows you to access properties from objects or elements from arrays by their keys or positions. Destructuring simplifies code and enhances readability, making it a valuable tool for React development.
  • In the context of React components, you can destructure props to extract specific properties directly.
  • For example, if you have a prop library, instead of using props.library, you can destructure it like this: { library }.
    • In the  index.js file, pass in a library property to our App component (<App library="React" />)
    • Go to App.js and add pass in props to the function and put it in the h1 as {props.library} replacing the text 
    • In index.js file and pass in a library property to our App component (<App library="GraphQL" />)
  • When working with arrays, array destructuring lets you assign variable names based on the position of elements. This concept is essential for managing state and props efficiently in React applications.
    • For instance, you can destructure the first element of an array like this: const[firstCity] = [Seattle, Tacoma, Bothell].

04_04 Understanding the useState Hook

Managing state in a React application is crucial, and the modern way to handle state variables is by using the useState function. Here are the key points:

  • To manage state in a React component, import the useState function from the React library.
import React, { useState } from 'react';
  • useState returns an array with two values: the current state value and a function to update the state.
  • You can initialize the state by passing an initial value to useState. For example, useState("happy") sets the initial state to “happy”.
  • To give the state variable a name, you can use array destructuring. For instance, const [emotion, setEmotion] = useState("happy") creates a state variable named emotion and a corresponding function setEmotion to update it.
  • You can use the state value in your component’s JSX, allowing it to be displayed dynamically.For example:
    Current emotion is {emotion}.
  • To update the state, you can call the function returned by useState (e.g., setEmotion("sad")) with the new state value as an argument.
    <button onClick={() => setEmotion("sad")}> SAD </button>
  • State variables can represent various data types, such as strings, Booleans, objects, or arrays, depending on your application’s needs.

In summary, useState is a fundamental React hook for managing and updating state variables, making it easier to create dynamic and interactive components.

04_05 Working with useEffect

The useEffect hook in React is used to manage side effects that are not directly related to a component’s render. It’s typically used for tasks like logging messages, loading data, or working with animations. The useEffect hook takes two arguments:

  1. A function: This function contains the code that performs the side effect. It will be executed when certain conditions are met.
  2. An array of dependencies: This array specifies when the effect should run. If it’s an empty array, the effect runs once after the initial render. If it includes specific dependencies (e.g., state variables), the effect runs whenever those dependencies change.

In the example provided, a console.log message is logged using useEffect to demonstrate a side effect. The effect runs once after the initial render because an empty array is passed as the second argument.

useEffect(() => {
   console.log(It's ${emotion} around here) }, [] ) // this second argument is the (empty) dependency array.

You can customize the behavior of useEffect by specifying which dependencies trigger the effect’s execution. If any of the dependencies change, the effect will run again. This is useful for handling dynamic updates based on changes in state variables or props.

04_06 Understanding the dependency array

  • useState and useEffect can be used together to manage multiple state variables in a React component.
  • In the example, two state variables, emotion and secondary, are created using useState.
  • Buttons are used to update these state variables when clicked.
  • useEffect is used to log the values of the state variables when they change.
  • The dependency array in useEffect specifies when the effect should run, allowing control over when the log messages are displayed.
  • You can include multiple state variables in the dependency array to trigger the effect when any of them change.

04_07 Incorporating useReducer

  • Create a checkbox in a React component.
  • Use the useReducer hook to manage the checkbox’s state.
const [checked, setChecked] = useReducer((checked => !checked, false);

<input type="checkbox"  value={checked} onChange={setChecked}>

<label>{checked ? => "checked" : "not checked"}</label>
  • Initially, the checkbox starts as unchecked with a label displaying “not checked.”
  • When the checkbox is clicked, the state toggles between checked and unchecked.
  • The label reflects the changes in the checkbox state.
  • Use useState to manage the checkbox state, including the checked state variable and setChecked function.
  • Refactor code to employ the useReducer hook, resulting in a cleaner approach for handling state changes.
  • Both methods achieved the same outcome of toggling the checkbox state and updating the label accordingly but useReducer is slightly cleaner because it takes the function out of the onChange and puts it as its first argument.

 

 

Skip to toolbar