๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ปWEB FrontEnd/ํ”„๋ ˆ์ž„์›Œํฌ React

Redux (1) : props ์—†์ด state ๊ณต์œ  ๊ฐ€๋Šฅ

Redux

Redux๋Š” props ์—†์ด state๋ฅผ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ฃผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๋‹ค.

 

1. Redux ์„ค์น˜

npm install @reduxjs/toolkit react-redux

โ€ป redux toolkit : redux์˜ ๊ฐœ์„ ๋ฒ„์ „ (๋ฌธ๋ฒ•์ด ์ข€ ๋” ์‰ฌ์›Œ์ง)  

 

๊ทผ๋ฐ ์„ค์น˜ํ•˜๊ธฐ ์ „์— package.json ํŒŒ์ผ์„ ์—ด์–ด์„œ "react", "react-dom" ํ•ญ๋ชฉ์˜ ๋ฒ„์ „์„ ํ™•์ธํ•œ๋‹ค. ์ด๊ฑฐ ๋‘๊ฐœ๊ฐ€ 18.1.x ์ด์ƒ์ด๋ฉด ์‚ฌ์šฉ๊ฐ€๋Šฅํ•˜๋‹ค. 

โ–ฒ ๊ทธ๊ฒŒ ์•„๋‹ˆ๋ฉด ์ง์ ‘ ๋‘๊ฐœ๋ฅผ 18.1.0 ์ด๋ ‡๊ฒŒ ์ˆ˜์ •ํ•œ ๋‹ค์Œ ํŒŒ์ผ์ €์žฅํ•˜๊ณ  ํ„ฐ๋ฏธ๋„์—์„œ npm install ๋ˆ„๋ฅด๋ฉด ๋œ๋‹ค. 

 

 

2. Redux ์…‹ํŒ…

โ‘  ์•„๋ฌด๊ณณ(์˜ˆ๋ฅผ ๋“ค๋ฉด, src ํด๋” ์•ˆ)์ด๋‚˜ state๋“ค์„ ๋ณด๊ด€ํ•˜๋Š” ํŒŒ์ผ์ธ store.js ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์„œ ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ๋ณต๋ถ™ํ•ด์ค€๋‹ค. 

(src/store.js)

import { configureStore } from '@reduxjs/toolkit'

export default configureStore({
  reducer: { }
})

 

โ‘ก index.js ํŒŒ์ผ๊ฐ€์„œ Provider ๋ผ๋Š” ์ปดํฌ๋„ŒํŠธ์™€ ์•„๊นŒ ์ž‘์„ฑํ•œ ํŒŒ์ผ์„ import ํ•ด์˜จ๋‹ค. 

๊ทธ๋ฆฌ๊ณ  ๋ฐ‘์— <Provider store={importํ•ด์˜จ๊ฑฐ}> ์ด๊ฑธ๋กœ <App/> ์„ ๊ฐ์‹ธ๋ฉด ๋œ๋‹ค. 

๊ทธ๋Ÿผ ์ด์ œ <App>๊ณผ ๊ทธ ๋ชจ๋“  ์ž์‹์ปดํฌ๋„ŒํŠธ๋“ค์€ store.js์— ์žˆ๋˜ state๋ฅผ ๋ง˜๋Œ€๋กœ ๊บผ๋‚ด์“ธ ์ˆ˜ ์žˆ๋‹ค.

(index.js)

import { Provider } from "react-redux";
import store from './store.js'

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

 

 

3. Redux store์— state ๋ณด๊ด€ํ•˜๋Š” ๋ฒ• 

step 1. createSlice( ) ๋กœ state ๋งŒ๋“ค๊ณ 

createSlice( ) ์ƒ๋‹จ์—์„œ import ํ•ด์˜จ ๋‹ค์Œ์—

{ name : 'state์ด๋ฆ„', initialState : 'state๊ฐ’' } ์ด๊ฑฐ ๋„ฃ์œผ๋ฉด state ํ•˜๋‚˜ ์ƒ์„ฑ๊ฐ€๋Šฅ 

(createSlice( ) ๋Š” useState( )์™€ ์šฉ๋„๊ฐ€ ๋น„์Šท)

 

step 2. configureStore( ) ์•ˆ์— ๋“ฑ๋ก

state ๋“ฑ๋ก์€ configureStore( ) ์•ˆ์— { ์ž‘๋ช… : createSlice๋งŒ๋“ ๊ฑฐ.reducer } ๋กœ ๋“ฑ๋ก

import { configureStore, createSlice } from '@reduxjs/toolkit'

let user = createSlice({
  name : 'user',
  initialState : 'kim'
})

export default configureStore({
  reducer: {
    user : user.reducer
  }
}) 

 

 

4. Redux store์— ์žˆ๋˜ state ๊ฐ€์ ธ๋‹ค์“ฐ๋Š” ๋ฒ•

์•„๋ฌด ์ปดํฌ๋„ŒํŠธ์—์„œ useSelector((state) => { return state } ) ์“ฐ๋ฉด store์— ์žˆ๋˜ ๋ชจ๋“  state ์‚ฌ์šฉ ๊ฐ€๋Šฅ 

(Cart.js)

import { useSelector } from "react-redux"

function Cart(){
  let a = useSelector((state) => { return state } )
  console.log(a)

  return (์ƒ๋žต)
}

์ด๋Ÿฐ ์‹์œผ๋กœ ์“ฐ๋ฉด ์ข€ ๋” ํŽธ๋ฆฌํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

let a = useSelector((state) => state.user )