Redux #2

김상현·2020년 6월 23일
0

React

목록 보기
13/16

Redux-Hook

기존 방식으로 Redux를 사용하는 경우 mapStateToProps를 이용해서 props내 state를 정의하고, connect를 이용해서 props를 바인딩하는 복잡한 행동을 해야한다.
하지만 react-redux의 useSelector와 useDispatch라는 hook을 이용하면 편하게 구현할 수 있다.


  • 기존의 방식
const Profile = (props) => {
  const { profile, updateProfile, thunkGetProfile } = props;

  // update id
  const updateId = () => {
    updateProfile({
      id: 'test',
    });
  };

  // update id twice
  const updateId2 = () => {
    updateProfile({
      id: 'test2',
    });
  };
  
  return (
    <div>
      <h1>useState, useEffect Example</h1>
      Profile! <br />
      ID: {profile.id} <br/>
      ButtonClick Count is: {counter} <br />
      <button onClick={updateId}>Update profile</button>
      <button onClick={updateId2}>Update profile</button>
    </div>
  );
};

const mapStateToProps = (state: AppState) => ({
  profile: state.profile,
});

export default connect(
  mapStateToProps,
  { getProfile, updateProfile, thunkGetProfile }
)(Profile);

  • useSelector와 useDispatch 사용
const Profile = (props) => {
  const dispatch = useDispatch();
  const profile = useSelector((store) => store.example.profile);

  // update id
  const updateId = () => {
    dispatch(updateExampleProfile({ id: 'test' }));
  };

  // update id twice
  const updateId2 = () => {
    dispatch(updateExampleProfile({ id: 'test2' }));
  };
  
  return (
    <div>
      <h1>useState, useEffect Example</h1>
      Profile! <br />
      ID: {profile.id} <br/>
      ButtonClick Count is: {counter} <br />
      <button onClick={updateId}>Update profile</button>
      <button onClick={updateId2}>Update profile</button>
    </div>
  );
};

0개의 댓글