Programming/React

[Redux] Redux 기본 개념

리버김 2023. 7. 7.
Redux: 상태관리 라이브러리

Redux를 쓰는 이유

  1. props 문법 귀찮을 때
  2. state 변경을 관리
  3. Redux 설치 후 store.js 파일에 state들을 보관함으로써 props가 필요 없게 된다.

 

사용 예제

1. state 보관하기

// index.js

import { Provider } from 'react-redux';
import { createStore } from 'redux';

const 체중 = 100;

function reducer(state = 체중, action) {
  return state
}

let store = createStore(reducer)

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
  document.getElementById('root')
)

 

2. state 가져와서 사용하기

// App.js

import './App.css';
import { useSelector } from 'react-redux'

function App() {
  const 꺼내온거 = useSelector( (state) => state );
  
  return (
    <div className="App">
      <p>나의 몸무게 : {꺼내온거}</p>
    </div>
  );
}

export default App;

 

3. Redux 스타일로 state 수정하기

컴포넌트들은 미리 정의된 형식(= reducer)대로의 수정 '요청'만 가능하다. dispatch를 사용하여 각 컴포넌트에서 state를 수정 요청한다.
// index.js

...

function reducer(state = 체중, action) {
  if (action.type === '증가') {
    state++;
    return state
  } else if (action.type === '감소') {
    state--;
    return state
  } else {
    return state
  }
}

...​
// App.js

...
const dispatch = useDispatch() // 수정토록 하는 함수

  return (
    <div className="App">
      <p>님의 처참한 몸무게 : {꺼내온거}</p>
      <button onClick={() => { dispatch({ type : '증가' }) }}>더하기</button>
    </div>
  );
}

export default App;

 

src

https://www.youtube.com/watch?v=QZcYz2NrDIs 

반응형

댓글