React Udemy #17: Customs Hooks in depth

JEUNGBIN HAN·2023년 1월 17일

React-Udemy-Lecture

목록 보기
11/12
post-thumbnail

What is custom hooks?

  1. functions that contain some reusable Logic
  2. custom hooks usually reuse buit-in hooks(useState, useEffect)
  3. Usually easiest to extract logic into a hook, rather than making a hook first 일반적으로 후크를 먼저 만드는 것보다 후크에 논리를 추출하는 것이 더 쉽습니다

The demo

  1. Make a tiny demo conponent with a tiny bit of logic
  2. Learn a design process to extract that logic into a custom hook
  3. Go back to sortableTable and repeat the design process

Sample component

  1. Make a component that shows a counter
  2. It should console.log the count every time it changes(useEffect)
  3. It should accept as 'initialCount' as a prop

CounterPage.js

import React, { useEffect, useState } from "react";
import Button from "../components/Button";

export default function CounterPage({ initialCount }) {
  const [count, setCount] = useState(initialCount);

  useEffect(() => {
    console.log(count);
  }, [count]);

  const handleClick = () => {
    setCount(count + 1);
  };
  return (
    <div>
      <h1>Count is {count}</h1>
      <Button onClick={handleClick}>Increment</Button>
    </div>
  );
}

App.js

        <Route path="/counter">
          <CounterPage initialCount={10} />
        </Route>

Custom Hook Creation

Inside the CounterPage.js
We have [count, useEffect, handleClick, JSX ]

count, useEffect, handleClick =>
Three chunks of code that
1. Creates number state based on an initial value
2. Logs that value any time it changes
3. Provides a way to change that value

Extract those threee chunks and make a reusable hook

This will get you pretty far
1. Find code in a component related to a single piece of state
2. Copy paste it all into a helper function
3. Fix all the broken references
4. you have a hook

useCounter()
[count, useEffect, handleClick]

Brute-Force Hook Creation

  1. Make a function called 'useSomething'
function useSomething(){}
  1. Find all the non-JSX expressions that refer to 1-2 related pieces of state

  2. Cut them all out, paste them into 'useSomething'

function useSomething() {
  const [count, setCount] = useState(initialCount);

  useEffect(() => {
    console.log(count);
  }, [count]);

  const handleClick = () => {
    setCount(count + 1);
  };
}

4.Find 'not definded' errors in your component
=> count, handleClick
5. In your hook, return an object that contains the variables that component needs.

function useSomething() {
....

  return {
    count,
    handleClick,
  };
}
  1. In the component, call your hook destructure the properties the component needs
const {count, handleClick} = useSomething()
  1. Find 'not definded' errors in the hook, pass the missing variables in an arguments to the hook
    => initialCount
function useSomething(initialCount) {
  const [count, setCount] = useState(initialCount);

...
}

export default function CounterPage({ initialCount }) {
  const { count, handleClick } = useSomething(initialCount);
  return (
    <div>
      <h1>Count is {count}</h1>
      <Button onClick={handleClick}>Increment</Button>
    </div>
  );
}
  1. Rename the hook
  2. Rename returned properties

export default function CounterPage({ initialCount }) {
function useCounter(initialCount) {
  const [count, setCount] = useState(initialCount);

  useEffect(() => {
    console.log(count);
  }, [count]);

  const increment = () => {
    setCount(count + 1);
  };

  return {
    count,
    increment,
  };
}

  const { count, increment } = useCounter(initialCount);
  return (
    <div>
      <h1>Count is {count}</h1>
      <Button onClick={increment}>Increment</Button>
    </div>
  );
}
profile
Web Developer

0개의 댓글