React Udemy #8: Context Hooks๐Ÿ˜ˆ

JEUNGBIN HANยท2022๋…„ 12์›” 16์ผ

React-Udemy-Lecture

๋ชฉ๋ก ๋ณด๊ธฐ
4/12
post-thumbnail

Intro Context

An Alternative to Props is Context

Context is not a replacement for Props , Redux

Using context

  1. Create the Context
import { createContext} from "react";

const BooksContext = createContext();

BookContext(App)

  • Proviser = Component used to specify what data we want to share
< BooksContext.Provider />
  • Comsumer = Component used to get access to data
  1. Specity the data that will be shared
    <BooksContext.Provider value={valueToShare}>
      {children}
    </BooksContext.Provider>
  • value = 'value' props is special. This is what will be shared with rest app

  • {valueToShare} = Data being shared could be any (number, string, array , object)

  • {children} = This component can now access the value shared in context

  1. Consume the data
import {useContext } from "react";
import BooksContext from "../context/books";

function App() {
  const { num } = useContext(BooksContext);
  return 
  <>{num}</>
  }

Changing Context Value

import { createContext, useState, useCallback } from "react";

const BooksContext = createContext();

function Provider({ children }) {
// custom Provider
  const [books, setBooks] = useState([]);
  
    const valueToShare = {
    books,
    deleteBookById,
    editBookById,
    createBook,
    fetchBooks,
  };

  return (
    <BooksContext.Provider value={valueToShare}>
    // valueToShare object we want to share
      {children}
    </BooksContext.Provider>
  );
}

When 'books' state is updated, this component will rerender along with all its component.

Application VS Component state

Application state : Data that is used by many different components

Component State : Data that is used by very few component

=> Both of those are still the same exact "state" we're been working on
=> These terms are a way to figure out how to hest design your state

Reusable Hooks

Hooks = Func that add additional features to a component.
useState, useEffect...

custom Hooks = functions we write to make reusable bits of logis

import {useContext } from "react";
import BooksContext from "../context/books";

function App() {
  const { fetchBooks } = useContext(BooksContext);
  // we always use those two togethre useContext(BooksContext)
profile
Web Developer

0๊ฐœ์˜ ๋Œ“๊ธ€