ContextAPI, React Redux

18326 단어 ReactReact

1. ContextAPI

강의 링크

1) createContext, Provider

createContext

Provider

store의 저장소이며 Context.Provider의 value를 return하여 데이터를 전달

// MovieContext.js

import React, { useState, createContext } from 'react';

// CREATECONTEXT
export const MovieContext = createContext();

// PROVIDER
export const MovieProvider = props => {
    const [movies, setMovies] = useState([
        {
            name: 'Harry Potter',
            price: '$10',
            id: 1
        },
        {
            name: 'Game of Thrones',
            price: '$10',
            id: 2
        },
        {
            name: 'Inception',
            price: '$10',
            id: 3
        }
    ]);
    return (
        <MovieContext.Provider value={[movies, setMovies]}>
            {props.children}
        </MovieContext.Provider>
    );
};

2) useContext

useContext()를 통해 Provider의 state를 사용할 수 있다.

// MovieList.js

import React, { useState, useContext } from 'react';
import Movie from './Movie'
import { MovieContext } from './MovieContext'

const MovieList = () => {

    const [movies, setMovies] = useContext(MovieContext);

    return (
        <div>
            {movies.map(movie => (
                <Movie name={movie.name} price={movie.price} key={movie.id} />
            ))}
        </div>
    );
};

export default MovieList;
// Movie.js

import React from 'react'

const Movie = ({ name, price }) => {
    return (
        <div>
            <h3>{name}</h3>
            <p>{price}</p>
        </div>
    );
};

export default Movie;
// App.js

import React from 'react';
import MovieList from './MovieList'
import { MovieProvider } from './MovieContext'

function App() {
  return (
    <MovieProvider>
      <div className='App'>
        <MovieList />
      </div>
    </MovieProvider>
  );
}

export default App;

2. React Redux

강의 링크

상태관리 매니저(ex. ContextAPI, MobX)이며
기존 부모 컴포넌트로부터 자식 컴포너트으로 한방향 전달하는 단점을
스토어에 상태를 모아놓고 어떤 컴포넌트에서든지 상태를 가져올 수 있다.

$ npm i redux react-redux
redux : 상태 관리
react-redux : 리덕스를 리액트에 사용 가능하게

import { createStore, useSelector } from 'redux'

// STORE : GLOBALIZED STATE
let store = createStore(counter);

// ACTION : DESCRIBE "WHAT YOU WANNA DO"
// FUNCTION -> RETURN OBJECT
const increment = () => {
  return {
    type: 'INCREMENT'
  }
}
const decrement = () => {
  return {
    type: 'DECREMENT'
  }
}

// REDUCER : DESCRIBE "CHECK ACTION THEN TRANSFORM STATE TO NEXT STATE"
// FUNCTION -> RETURN OBJECT
const counter = (state = 0, action) => {
  switch(action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

// combineReducers : USE REDUCER TOGETHER
const allReducers = combineReducers({
  counter: counterReducer // === counterReducer
})


// Disaply it in the console
store.subscribe(() => console.log(store.getState()));

// DISPATCH : EXECUTE ACTION
store.dispatch(increment()); // 1
store.dispatch(decrement()); // 0
store.dispatch(decrement()); // -1


// useSelector : ACCESS TO STATE
const counter = useSelector(state => state.counter);

좋은 웹페이지 즐겨찾기