210517 React with NextJS TIL - Next Redux Wrapper, HYDRATE, redux-thunk, 제너레이터 함수에 대한 이해, redux-saga

2021/05/17 - redux-thunk 내용추가

ReactJS with NextJS

Next Redux Wrapper

일반적으로 React에 Redux를 붙일 때에는 하나의 Redux store만 존재하기 때문에 어렵지 않다.
하지만 Next.js에서 Redux를 사용하게 되면 여러 개의 Redux store가 생성된다.
그 이유는 Next.js에서는 User가 Request를 보낼때마다 Redux store를 새로 생성하기 때문이다. 그리고 Next.js에서 제공하는 getInitialProps와 getServerSideProps에서도 Redux store에 접근이 가능하도록 해야되기 때문에 NextJS에서 Redux를 붙일때 꽤나 복잡하다. 하지만 이를 간편하게 해주는 라이브러리가 있는데 바로 Next Redux Wrapper이다.

next redux wrapper 설치

/store/configureStore.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { createWrapper } from 'next-redux-wrapper';
import { createStore } from 'redux';
import reducer from '../reducers';

const configureStore = () => {
const store = createStore(reducer);
return store;
};

const wrapper = createWrapper(configureStore, {
debug: process.env.NODE_ENV === 'development'
});

export default wrapper;
Read more

210515 React with NextJS TIL - Next.js에서 styled-components를 사용하기 위한 설정

ReactJS with NextJS

참고 : https://github.com/vercel/next.js/tree/master/examples/with-styled-components

Next.js에서 styled-components 사용하기

Next.js에서 styled-components를 사용하려면 몇 가지 설정이 필요하다.

(1) babel-plugin-styled-components 설치하기

이 패키지를 설치하는 이유는 Next에서 최초로 SSR이 된 이후에 내부 라우팅을 통해 페이지가 이동하면서 CSR을 하게 되는데, className의 해시값이 서버에서 생성되는 값과 브라우저에서 생성되는 값이 불일치하게 되면서 에러가 발생하기 때문에 설치해줘야 한다.

1
npm i -D babel-plugin-styled-components

(2) .babelrc 파일 생성하기

1
2
3
4
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}

(3) pages 폴더 아래에 _document.js 파일 생성하기

참고: https://nextjs.org/docs/advanced-features/custom-document

Read more

210426 React with NextJS TIL - NextJ의 pages와 layout, _app.js, NextJS - Head, NextJS 전용 router, eslint 설정, NextJS v9의 새로운 기능들, front-end/back-end 서버간의 CORS 설정

ReactJS with NextJS

NextJS 프로젝트 기본 설정

next v9

1
$ npm i next@9

package.json

1
2
3
4
"script": {
"dev": "next",
"build": "next build"
}

NextJS의 js파일에서는 import React from 'react';구문이 필요없다.

그 이유는 NextJS 프레임워크가 pages 폴더내의 js파일들을 code splitting된 개별적인 page component로 만들어주기 때문이다.

pages와 layout

React에서는 react-router로 routing 경로를 설정해줘야 했는데, NextJS는 front server를 가지고 있기 때문에 pages폴더내의 파일의 이름을 url로 자동 mapping 시켜준다.

pages/profile.js => /profile
pages/signup.js => /signup
pages/about/lee.js => /about/signup

Read more