JunilHwang / blog-comment

TIL comments
1 stars 0 forks source link

TIL/Javascript/Design/Vanilla-JS-Make-useSate-hook/ #27

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Vanilla Javascript로 React UseState Hook 만들기 | 개발자 황준일

React의 UseState Hook의 작동방식에 대해 고민해보고, 구현해보고, 최적화하는 내용을 다룹니다.

https://junilhwang.github.io/TIL/Javascript/Design/Vanilla-JS-Make-useSate-hook/?fbclid=IwAR3DbpK2gDVnAa70xMwrWItMMrJQT69TUnQEmC5_2NHc0keDJTdTlaz0Nzc

heyman333 commented 2 years ago

대단하십니다 ㅠㅠ

pocojang commented 2 years ago

재미있게 보고 갑니다~ /src/core/MyReact.js 에 오타가 하나있어요!

JunilHwang commented 2 years ago

@devJang 오탈자도 발견해주시다니! 감사합니다 ㅎㅎ

chichchic commented 2 years ago

좋은 글 감사합니다. 그런데 states와 currentStateKey를 사용하여 여러 state를 저장하는 부분에(고양이 야옹야옹부분) useState에 key값 따로 저장하는 코드와 setState내부 해당 key의 값을 수정하도록해야 원하는데로 실행될것같네요. 확인 부탁드릴게요 :)

JunilHwang commented 2 years ago

@chichchic 안녕하세요! 흠.. 지금 코드도 정상적으로 작동하고 있지 않나요? 일단 지금은 특별한 문제가 없는 것 같아서요!

chichchic commented 2 years ago

bottom-up분석 가장 아래있는 예제에 코드 일부가누락됐다는거였어요!! 코드 실행시켜보면 정상작동이 안됩니다.

JunilHwang commented 2 years ago

@chichchic

let currentStateKey = 0; // useState가 실행 된 횟수
const states = []; // state를 보관할 배열
function useState(initState) {
  // initState로 초기값 설정
  if (states.length === currentStateKey) {
    states.push(initState);
  }

  // state 할당
  const state = states[currentStateKey];
  const setState = (newState) => {
    // state를 직접 수정하는 것이 아닌, states 내부의 값을 수정
    states[currentStateKey] = newState;
    render();
  }
  currentStateKey += 1;
  return [ state, setState ];
}

function Counter () { /*생략*/ }
function Cat () { /*생략*/ }

const render = () => {
  app.innerHTML = `
    <div>
      ${Counter()}
      ${Cat()}
    </div>
  `;
  // 이 시점에 currentStateKey는 2가 될 것이다.
  // 그래서 다시 0부터 접근할 수 있도록 값을 초기화 해야 한다.
  currentStateKey = 0;
}

이 코드 말씀하시는거죠? 일부로 일부 코드는 흐름에 방해될까봐 생략한거였는데.. ㅠㅠ https://github.dev/JunilHwang/simple-use-state/blob/master/04-multi-state-success/index.html 혹시 위에 링크에 있는 코드로 해보면 잘 되시나요?

chichchic commented 2 years ago

아 일부러 생략하신거였군요. 하나씩 따라해보면서 진행하다 저부분 안되길래 코드 아래 버튼 동작 부분 코드 열어서 봤는데 코드 일부가 다르길래 누락된건줄 알았네요.

nwleedev commented 2 years ago

어떻게 useState가 작동하는지 알 수 있게 되었네요 존경합니다.

chebread commented 2 years ago

황준일 개발자님 코드 너무 잘 봤습니다! 혹시 useEffect도 어떻게 동작하는지 구현해 주실 수 있나요? 부탁드립니다!

909back commented 1 year ago

vanillaJS로 useState를 구현해보다가 글을 읽게 되었는데 많은 도움이 됐습니다 정말 대단하십니다👍