Blog Day 40: React State, insertDash

Inseo Park·2021년 8월 18일
0

Path to Data Scientist

목록 보기
38/58
post-thumbnail

1. TIL (Today I Learned)

State

The "state" of the application

In the state & props video, it was said that state is a value that can be changed inside a component like Toggle Switch or Counter. What would be a "state" in a real application. Let's take a shopping mall shopping cart as an example. The user distinguishess between the items to be purchased and the items not to be purchased at the moment by checking the checkboxes. If we divide this into th status in the shopping cart, it is a checked status & unchecked status.

The implementation of the checkbox in code is as follows. In the example below, the text displayed simply depends on the checked status, but if this is applied to the shopping mall, the number of items to be purchased on the purchase amount will change depending on whether the check is made or not, and the user's screen will also change accordingly. As such, mutable values within a component, i.e. state, should be treated as React state.

import React, { useState } from "react";
import "./style.css";

function CheckboxExmaple() {
  const [isChecked, setIsChecked] = useState(false);
  
  const handleChecked = (event) => {
    setIsChecked(event.target.checked);
  };
  
  return (
    <div className="App">
      <input type="checkbox" checked={isChecked} onChange={handleChecked} />
      <span>{isChecked ? "Checked!" : "Unchecked"}</span>
    </div>
  );
};

export default CheckboxExample;

State hook, useState

useState Usage

React provides a special function called useState as one way to handle state. Let's take a look at how this function is used and how it works using the checkbox example above.

To use useState, we need to call useState from React. Let's call useState with the import keyword.

import { useState } from "react";

After that, useState is called inside the component. Calling useState is equivalent to declaring a variable called "state", which can be named anything. Normally, variables disappear when the function ends, but the state variable is not destroyed by React when the function ends.

From a syntatical point of view, isChecked and setIsChecked in the example below are variables assigned by destructuring the return value of useState.

function CheckboxExample() {
  const [isChecked, setIsChecked] = useState(false);
  
function CheckboxExample() {
  const [isChecked, setIsChecked] = useState(false);
  // is same as
  
  const StateHookArray = useState(false);
  const isChecked = StateHookArray[0];
  const setIsChecked = StateHookArray[1];
}

Calling useState returns an array, where the first element of the array is the current state variable, and the 2nd element is a function that can update this variable. The value passed as an argument to useState is the initial value of state.

const [state storage variable, state update function] = useState(state initial value);

Let's write the actual code.

function CheckboxExample() {
  const [isChecked, setIsChecked] = useState(false);
  
  • isChecked: variable to store state
  • setIsChecked: function to change state isChecked
  • useState: State hook
  • false: state initial value

To use the value stored in this state variable, you can call it directly inside the JSX element and use it. Here, because isChecked has a boolean value, we use the ternary operator to get different results depending on whether it is true or false.

<span>{isChecked ? "Checked!!" : "Unchecked"}</span>

Update State

  • To update the state, call setIsChecked, a function that can update the state variable.
  • In this example, isChecked should be changed according to the value change of the input[type=checkbox] JSX element. If the value is changed to checked in the browser, isChecked in React should also change, right?
  • When the value of the input[type=checkbox] element changes, the onChange event occurs, and the event handler function is activated, did you get used to the pattern by working with DOM?
  • The same goes for React when the user changes the checkbox value, the onChange event calls the event handler function handleChecked, which in turn calls setIsChecked. When setIsChecked is called, the isChecked variable is updated according to the call result, and React passes the new isChecked variable to the Checkbox example component to re-render the component.
function Checkbox Example() {
  const [isChecked, setIsChecked] = useState(false);
  const handleChecked = (event) => {
    setIsChecked(event.target.checked);
  };
  
  return (
    <div className="App">
      <input type="checkbox" checked={isChecked} onChange={handleChecked} />
      <span> {isChecked ? "Checked!!" : "Unchecked"}</span>
    </div>
  );
};

Precautions

So far, we have learned how to use state hooks. Let's learn about the precautions when using the state hook.

  • React components are newly called and re-rendered when the state changes.
  • React state needs to be changed by a state change function call. Do not force changes. The use of state-changing functions is a promise between React and the developer, so you must keep it. If you try to force the change, re-rendering does not work or the state is not changed properly.

insertDash

Take a string as input and return a string with '-' added between consecutive odd numbers.

function insertDash(str) {
  let result = '';
  for (i = 0; i < str.length; i++) {
    if (str[i] % 2 !== 0 && str[i-1] % 2 !== 0) {
      result = result + '-';
    }
    result = result + str[i];
  }
  return result;
}
  
  

2. 3 Things to be Thankful for

  1. Thankful for God reminding me to rely on you only.
  2. Thankful for a blessing day to have a good exeperience.
  3. Thankful for having hope on my future.

3. Ideas and Things to think about

  1. I don't want to be the person who always does not want to make mistakes and be perfect. Today's world, most people wants perfection but that can be the worst thing a person can do. Because a single mistake will cause that person to feel really down. That is a poison to life.
profile
my journey to become a data scientist.

0개의 댓글