Skip to content

Latest commit

 

History

History
205 lines (147 loc) · 8.05 KB

react-part-3-state.md

File metadata and controls

205 lines (147 loc) · 8.05 KB

React State

Projected Time

Total: ~ 2 hours

  • Lesson: 45 mins
  • Guided Practice: 30 mins
  • Independent Practice: 30 mins
  • Check for understanding: 5 mins

Prerequisites

Motivation

React allows developers to create large web applications that can change data without reloading the page. The changes are managed as the component's state. React watches state, and only changes parts of the page where the state changes.

Facebook created React as a framework to create reusable components, like posts or comments, and allow the user to see updates instantly. For example, submitting a new comment would add that new data to the state. Because the state changed in the post, the comment section would automatically update, while the image or title wouldn't have to update. This takes a lot less computing power, and it is more satisfying than having to refresh the page to notice the change.

Objectives

Participants will be able to:

  • Explain some advantages of React state
  • Explain the main difference between React props and state
  • Become familiar with how state is implemented

Specific Things to Learn

  • What is React state?
  • What is the difference between React props and state?
  • When to use React props
  • When to use React state

Materials

See Lesson for how to use each.

Lesson

React State

State is the reactive part of react.

  • Spend 10 minutes looking at this code pen example of a simple toggle state: checked or unchecked. If you fork it you can experiment, or delete the comments to see just the code. https://codepen.io/alodahl/pen/YzZyaKe
  • Take a minute or two to look at the checkbox html in the inspector. Watch how the attributes change as you check and uncheck the box.

Props vs State

To put it plainly, the difference between props and state is whether you need external or internal management for your component. Props are what the component needs to receive to do its job, while state is what it manages on its own.

What are some real world examples? If we pretend these are components, this is how it would look:

Software Employee

  • Props to pass in: assignments, meetings
  • State to self-manage: time management, code creation, lunch

Dog

  • Props: food, water, let in or out
  • State: sleep/wake, emotions, running or sitting

Toaster

  • Props: start lever, timer setting
  • State: heat up based on start, pop-up based on timer, turn off after pop-up happens

Car

  • Props: // add 3 examples yourself - what does the driver control?
  • State: // add 3 examples yourself - what does a car control automatically?

Take 3 minutes to come up with examples for "Car". We'll practice using both props and state in the same component in Guided Practice.

Reading Time

Common Mistakes / Misconceptions

  1. It may take a few days for props v state to sink in - this is normal. For now, try to remember the basic reasons you would use one instead of the other. No need to memorize the syntax yet.
  2. Don't forget that JS variables inside JSX must be enclosed in curly braces. Example: <div className={props.classNames}>Hello {props.name}, your lights are {isLightOn ? "on" : "off"}</div>
  • Note that boolean isLightOn is the name of an example state.

Guided Practice

We'll create a random quote display using React. The application will display a random quote when a user clicks on button.

Starter Code

  1. QuoteGenerator - the top-level app
  2. QuoteText - displays the quote text and speaker name
  3. QuoteButton - user clicks on it to pick a new random quote

Test Data

The full set is in the starter code link above.

// Source: https://www.mentalfloss.com/article/53181/inspiring-quotes-10-influential-women-tech
const quotes = [
  {
    text:
      'A ship in port is safe, but that is not what ships are for. Sail out to sea and do new things.',
    source: 'Grace Hopper'
  }
  //...
];

const QuoteGenerator = () => (
  <div>
    <h2>Women in Tech Random Quotes</h2>
    <div>Quote Text</div>
    <button>Quote Button</button>
  </div>
);

ReactDOM.render(<QuoteGenerator />, document.querySelector('#react'));

Create the components for the quote generator app

You will need to replace the placeholders above with actual QuoteText and QuoteButton components.

For QuoteText, create a component that takes a quote prop that matches the shape of an element in the quotes array, with a text and speaker property.

const QuoteText = (props) => (
  <div>
    <p>{props.quote.text}</p>
    <h3>{props.quote.speaker}</h3>
  </div>
);

Now create a QuoteButton that has a button and a prop onClick that will be the function called when a user clicks on the button.

CodePen

const QuoteButton (props) => (
  <button onClick={props.onClick}>New Quote</button>;
);

Now that you have those two pieces, use them in the top-level QuoteGenerator component.

Create QuoteGenerator, the top-level component

const QuoteGenerator () => (
  <div>
    <h2>Women in Tech Random Quotes</h2>
    <QuoteText quote={currentQuote} />
    <QuoteButton onClick={() => {}} />
  </div>
);

Now you just have to define the onClick behavior so it changes the quote.

const QuoteGenerator () => {
  const getRandomQuote = () => {
    const randomIndex = Math.floor(Math.random() * quotes.length);
    return quotes[randomIndex];
  };

  const [currentQuote, setCurrentQuote] = useState(getRandomQuote());

  return (
    <div>
      <h2>Women in Tech Random Quotes</h2>
      <QuoteText quote={currentQuote} />
      <QuoteButton onClick={() => setCurrentQuote(getRandomQuote())} />
    </div>
  );
}

One of the most complex parts of this example is that setCurrentQuote manages the state, but it is passed down as a prop to QuoteButton. Because the quotes are controlled and displayed in QuoteGenerator, quotes have to be managed there. The way setCurrentQuote is passed through the onClick prop is a callback. When onClick happens, QuoteButton triggers its onClick function, but that function, setCurrentQuote, is still executed here in QuoteGenerator.

Independent Practice

For the next 30 minutes, practice accomplishing the task below. After that, you can peek at the finished CodePen.

Instead of random quotes, modify QuoteButton so it displays two buttons, Previous and Next that go through the quotes array in order.

  • On each new button's onClick method, change the state with setCurrentQuote(*add logic here*).
  • When you reach either end of the list, it's up to you if it "wraps around" to the other end or if the Previous or Next button are disabled on the ends.
  • When newly added, the state should be updated to display it as the current quote.

Finished Result

This CodePen has an example of a finished result.

Check for Understanding

  • Explain some advantages of React state.
  • Explain the main difference between React props and state.
  • If you aren't sure about either of these, write them down and figure it out with a peer before moving on.

Extensions (Optional)