React _ Router Hooks

LOOPY·2021년 8월 31일
0
post-thumbnail

👉🏻 useHistory, useLocation, useParams, useRouteMatch -> props 대신 사용하기


- 예제 1

export default function withRouter(function LoginButton(props)){
  
  console.log(props);
  
  function login(){
    setTimeout(()=>{
      props.history.push("/");
    }, 1000);
  }   
  
  return <button onClick={login}>로그인하기</button>;
}

-> withRouter로 LoginButton의 props 받아오는 방식 대신 Router Hook(useHistory) 사용

export default function LoginButton(){
  const history = useHistory();
  
  function login(){
    setTimeout(()=>{
      history.push("/");
    }, 1000);
  }
  
  return <button onClick={login}>로그인하기</button>;
}

- 예제 2

export default function Profile(props){
  
  const id = props.match.params.id;
  
  console.log(id, typeof id);
  
  return(
    <div>
      <h2>Profile Page!</h2>
      {id && <p>id is {id}.</p>}
    </div>
  );

}

-> props.match.params.id로 id 받아오는 방식 대신 Router Hook(useParams)로 useParams.id 사용

export default function Profile(props){
  
  const params = useParams();
  const id = params.id;
  
  console.log(id, typeof id);
  
  return(
    <div>
      <h2>Profile Page!</h2>
      {id && <p>id is {id}.</p>}
    </div>
  );

}

🌟 props로 처리보다 함수component / state / custom hook 등으로 처리하는게 더 깔끔!

profile
2년차 프론트엔드 개발자의 소소한 기록을 담습니다 :-)

0개의 댓글

관련 채용 정보