LoginSignup
3
0

More than 5 years have passed since last update.

React HooksでTutorialをやってみる(TypeScript)

Last updated at Posted at 2018-12-16

この記事はReact.js Advent Calendar 2018の15日目の記事です。

。。。完全に忘れていましたorz

という事で、公式のチュートリアルReact Hooksでやってみました。

コードはこちら

環境構築

create-react-app使います。

yarn create react-app react-tutorial-hooks --scripts-version=react-scripts-ts
cd react-tutorial-hooks
yarn add react@16.7.0-alpha.2 react-dom@16.7.0-alpha.2

Hooks使いどこ

Classを全てFunctionに変えて、useStateを使います。

/* before */
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true
    };
  }
/* after */
const App = () => {
  const [history, setHistory] = React.useState([
    {
      squares: Array(9).fill(null)
    }
  ]);
  const [stepNumber, setStepNumber] = React.useState(0);
  const [xIsNext, setXIsNext] = React.useState(true);

チュートリアルではこのぐらいしかなかったですね。。。

まとめ

普段、recompose使っているので特に違和感はなく「あぁ、withStateとかwithHandlersか」的な感覚でした。
今回はuseStateしか使っていませんが、他にも色々あるので調べていこうかなと思います。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0