state counter practice

Juyeon Lee·2022년 5월 2일
0

REACT 리액트

목록 보기
19/65

기본적인 counter 만드는걸 배워봄..
밑의 코드를 살펴보자

import React from "react"

export default function App() {
    /**
     * Challenge: 
     * Add functionality to the minus button
     */
    const [count, setCount] = React.useState(0)
    
    function add() {
        setCount(count + 1)
    }
    
    function subtract() {
        setCount(count - 1)
    }
    
    return (
        <div className="counter">
            <button className="counter--minus" onClick={subtract}></button>
            <div className="counter--count">
                <h1>{count}</h1>
            </div>
            <button className="counter--plus" onClick={add}>+</button>
        </div>
    )
}

이 코드를 보면 여기도

 const [count, setCount] = React.useState(0)

이렇게 destrcutring 해주고 기본값을 0으로 설정해줌..
혼자 했을 때 이부분을 틀렸음 ㅠㅠ
그리고

    function add() {
        setCount(count + 1)
    }
    
    function subtract() {
        setCount(count - 1)
    }

setCount에 간단하게 이렇게 해줘도 이 코드는 작동하는데
보통 이렇게 쓰지 않고 아래와 같이 callback function을 이용해서
쓴다고 한다.

import React from "react"

export default function App() {
    const [count, setCount] = React.useState(0)
    /**
     * Note: if you ever need the old value of state
     * to help you determine the new value of state,
     * you should pass a callback function to your
     * state setter function instead of using
     * state directly. This callback function will
     * receive the old value of state as its parameter,
     * which you can then use to determine your new
     * value of state.
     */
    function add() {
        setCount(prevCount => prevCount + 1)
    }
    // Challenge: update `substract` to use a callback function
    
    function subtract() {
        setCount(prevCount => prevCount - 1)
    }
    
    return (
        <div className="counter">
            <button className="counter--minus" onClick={subtract}></button>
            <div className="counter--count">
                <h1>{count}</h1>
            </div>
            <button className="counter--plus" onClick={add}>+</button>
        </div>
    )
}

callback함수를 arrow function으로 이용해서 쓴거다.
만약 arrow function 안쓰고 원래 function으로 쓰면
아래와 같다.

  function add() {
        setCount(function(oldValue) {
            return oldValue + 1
        })
    }
    

위의 코드에 관련된 퀴즈

  1. You have 2 options for what you can pass in to a
    state setter function (e.g. setCount). What are they?

a. New value of state (setCount(42))
->이건 위에서

function add() {
        setCount(count + 1)
    }

이렇게 했던걸 말한다.
b. Callback function - whatever the callback function
returns === new value of state
->이건 위에서

 function add() {
        setCount(prevCount => prevCount + 1)
    }

이렇게 했던걸 말한다.

  1. When would you want to pass the first option (from answer
    above) to the state setter function?
    Whenever you don't need the previous value of state to determine
    what the new value of state should be.
  1. When would you want to pass the second option (from answer
    above) to the state setter function?
    Whenever you DO need the previous value to determine the new value

4개의 댓글

comment-user-thumbnail
2024년 11월 16일

it is certainly wonderful along with meanful. it is certainly neat web site. Backlinks is incredibly valuable issue. you've got genuinely made it easier for some people whom pay a visit to web site and still provide these people usefull data. Bijoux québécois en ligne

답글 달기
comment-user-thumbnail
2024년 11월 19일

You might be allowed to submit brands, however, not back links, except if they may be accepted and also about matter. Iptv

답글 달기
comment-user-thumbnail
2024년 11월 20일

I've got not long ago started off some sort of blog site, the internet people produce here possesses served everyone enormously. Appreciate it intended for all of your current time period & do the job. iptv uk

답글 달기
comment-user-thumbnail
2024년 11월 25일

Debox's self-help book, available at https://debox.Co/debox-digital-book/, equips readers with strategies for confronting and overcoming past trauma. Utilizing cognitive-behavioral techniques, the book guides individuals through the process of identifying triggers related to their traumas. Through journaling exercises, readers engage in reflective practices to understand their emotional responses. The book presents case studies, such as individuals overcoming childhood abuse, to illustrate successful healing journeys. Practical exercises within the book are designed to strengthen resilience by developing coping mechanisms. Readers learn to reframe negative thought patterns, a step crucial for healing from traumatic experiences like betrayal or accidents. The inclusion of mindfulness activities aids in reducing symptoms of PTSD by promoting present-moment awareness. Support systems play a critical role, as demonstrated through examples of community healing circles fostering collective recovery. The book emphasizes the importance of setting realistic healing goals, preventing feelings of overwhelm during the recovery process. It encourages seeking professional therapy for trauma that persists despite self-help efforts, providing a directory of resources for additional support. healing past trauma with Debox

답글 달기