useEffect & Closure

ChungsikPark·2022년 7월 5일
0

함수형

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setTimeout(() => {
      reactotron.log(`You clicked ${count} times`);
    }, 3000);
  });
  
  return (
    <View>
      <Text>You clicked {count} times</Text>
      <TouchableOpacity onPress={() => setCount(count + 1)}>
        Click me
      </TouchableOpacity>
    </View>
  );
}

클래스형 1

class Counter1 extends Component {
  state = {
    count: 0
  };

  componentDidMount() {
    setTimeout(() => {
      reactotron.log(`You clicked ${count} times`);
    }, 3000);
  }

  componentDidUpdate() {
    setTimeout(() => {
      reactotron.log(`You clicked ${count} times`);
    }, 3000);
  }

  render() {
    return (
      <View>
        <Text>You clicked {this.state.count} times</Text>
        <TouchableOpacity onPress={() => this.setState({
          count: this.state.count + 1
        })}>
          Click me
        </TouchableOpacity>
      </View>
    )
  }
}

클래스형 2 (closure)

class Counter2 extends Component {
  state = {
    count: 0
  };

  componentDidMount() {
    const count = this.state.count; // "클래스형 1"과 다른 부분
    setTimeout(() => {
      console.log(`You clicked ${count} times`);
    }, 3000);
  }

  componentDidUpdate() {
    const count = this.state.count; // "클래스형 1"과 다른 부분
    setTimeout(() => {
      console.log(`You clicked ${count} times`);
    }, 3000);
  }

  render() {
    return (
      <View>
        <Text>You clicked {this.state.count} times</Text>
        <TouchableOpacity onPress={() => this.setState({
          count: this.state.count + 1
        })}>
          Click me
        </TouchableOpacity>
      </View>
    )
  }
}
profile
Blog by Chungsik Park

0개의 댓글