Built Portfolio Page - 7 (Code Cleaning)

Steps:

  1. Extract same logic and put it to a hook
  2. Replace code with the hook function

Extract same logic and put it to a hook

Add src/hooks/useSectionInView.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { useEffect } from "react";
import { useInView } from "react-intersection-observer";

import { useActiveSectionContext } from "@/context/ActiveSectionContext";
import type { SectionName } from "@/libs/types";

export function useSectionInView(sectionName:SectionName, threshold = 0.75){
const { ref, inView} = useInView({
threshold,
});
const { setActiveSection, timeOfLastClick } = useActiveSectionContext();

useEffect(()=>{
if( inView && Date.now() - timeOfLastClick > 1000 ) {
setActiveSection(sectionName);
}
},[inView, setActiveSection,timeOfLastClick,sectionName]);

return {
ref,
};
}

Replace code with the hook function

Intro.tsx

1
2
3
4
5
6
...
import { useSectionInView } from '@/hooks/useSectionInView';

export default function Intro() {
const { ref } = useSectionInView("Home",0.5);
...

About.tsx:

1
2
3
4
5
6
...
import { useSectionInView } from '@/hooks/useSectionInView';

export default function About() {
const { ref } = useSectionInView("About");
...

Project.tsx:

1
2
3

export default function Projects() {
const { ref } = useSectionInView("Projects",0.5);

请我喝杯咖啡吧~

支付宝
微信