Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react): useNetwork 신규 훅 추가 #194

Merged
merged 1 commit into from
Jun 2, 2024
Merged

Conversation

ssi02014
Copy link
Contributor

@ssi02014 ssi02014 commented Jun 1, 2024

Overview

Issue: #181

신규 useNetwork 훅을 추가합니다.

해당 훅은 React에서 제공하는 useSyncExternalStore훅을 통해 브라우저 네트워크 상태를 구독 후 online 여부(isOnline)에 대한 값을 반환하는 커스텀 훅입니다.

onlineCallback, offlineCallback props를 통해 네트워크가 변경됐을 때 특정 함수를 호출 할 수 있습니다.
해당 기능은 사용자가 서비스를 이용하다 갑자기 네트워크가 중단됐을 때 특정 행위를 할 수 있기 때문에 굉장히 강력한 기능입니다.

예를 들어, 아래와 같이 fallback 페이지로 이동시킬 수 있습니다.

const { isOnline } = useNetwork({
  onlineCallback: () => {
    // online으로 네트워크가 변경됐을 때 원하는 행위
  },
  offlineCallback: () => {
    navigate('/offline');
  },
});

https://ko.react.dev/reference/react/useSyncExternalStore#subscribing-to-a-browser-api
위 문서의 나오는 예제를 기반으로 작성됐지만 onlineCallback, offlineCallback 등의 기능들이 추가됐습니다.

참고

  • useSyncExternalStore를 사용함에 따라 react, react-dom의 peerDependency를 ^18 로 변경합니다.

PR Checklist

  • All tests pass.
  • All type checks pass.
  • I have read the Contributing Guide document.
    Contributing Guide

@ssi02014 ssi02014 added feature 새로운 기능 추가 @modern-kit/react @modern-kit/react labels Jun 1, 2024
@ssi02014 ssi02014 requested a review from Sangminnn June 1, 2024 09:15
@ssi02014 ssi02014 self-assigned this Jun 1, 2024
Copy link

changeset-bot bot commented Jun 1, 2024

🦋 Changeset detected

Latest commit: 5dd3739

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@modern-kit/react Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Comment on lines +46 to +48
const preservedSubscribe = usePreservedCallback((onStoreChange: () => void) =>
subscribe(onStoreChange, onlineCallback, offlineCallback)
);
Copy link
Contributor Author

@ssi02014 ssi02014 Jun 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useSyncExternalStore의 첫 번째 인자인 subscribe 함수는 onStoreChange를 필수로 받아오고 이를 호출해야 정상적으로 변화를 감지하고 리렌더링됩니다.

여기다 onlineCallback, offlineCallback 함수들을 추가로 다룰 수 있게 커링으로 구성합니다.

// useSyncExternalStore interface
export function useSyncExternalStore<Snapshot>(
  subscribe: (onStoreChange: () => void) => () => void,
  getSnapshot: () => Snapshot,
  getServerSnapshot?: () => Snapshot,
): Snapshot;

Comment on lines +14 to +16
const getServerSnapshot = () => {
return true;
};
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getServerSnapshot은 서버사이드 렌더링 시 getSnapshot의 초기값입니다.
초기값으로 true로 설정하였습니다.

Comment on lines +54 to +66
it('should return true for isOnline during server-side rendering', () => {
const TestComponent = () => {
const { isOnline } = useNetwork({
onlineCallback: onlineCallbackMock,
offlineCallback: offlineCallbackMock,
});
return <p>{isOnline ? 'online' : 'offline'}</p>;
};

const html = renderToString(<TestComponent />); // server side rendering

expect(html).toContain('online');
});
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

서버사이드렌더링 시 테스트를 위해 react-dom/server의 renderToString을 사용하였습니다.

@ssi02014
Copy link
Contributor Author

ssi02014 commented Jun 1, 2024

package.jsonpeerdependency1e2069c 에서 선 반영했습니다.

@ssi02014 ssi02014 force-pushed the feat/useNetwork branch 2 times, most recently from 126e642 to d49f69a Compare June 1, 2024 09:30
Copy link

codecov bot commented Jun 1, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.44%. Comparing base (af930a0) to head (d49f69a).

Current head d49f69a differs from pull request most recent head 5dd3739

Please upload reports for the commit 5dd3739 to get more accurate results.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #194      +/-   ##
==========================================
+ Coverage   95.43%   95.44%   +0.01%     
==========================================
  Files          81       81              
  Lines         810      812       +2     
  Branches      191      194       +3     
==========================================
+ Hits          773      775       +2     
  Misses         31       31              
  Partials        6        6              
Components Coverage Δ
@modern-kit/react 91.75% <100.00%> (+0.03%) ⬆️
@modern-kit/utils 100.00% <ø> (ø)

Copy link
Collaborator

@Sangminnn Sangminnn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드랑 테스트케이스 다 너무 깔끔하고 좋아보입니다! 👍x100
너무 고생많으셨습니다!

@ssi02014
Copy link
Contributor Author

ssi02014 commented Jun 2, 2024

@Sangminnn 감사합니다!! 해당 훅은 사용자가 갑자기 네트워크 상태가 오프라인이 됐을 때 운영하는 서비스에 아무런 행동을 취하지 않는 것보다 이런 상황을 대응할 수 있는 행동을 할 수 있다는게 굉장히 매력적인 훅이라고 생각이드네요!! 👍👍

@ssi02014 ssi02014 merged commit e12da88 into main Jun 2, 2024
1 of 2 checks passed
@ssi02014 ssi02014 deleted the feat/useNetwork branch June 2, 2024 05:52
@github-actions github-actions bot mentioned this pull request Jun 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature 새로운 기능 추가 @modern-kit/react @modern-kit/react
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants