1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React初心者のためのよく使う機能一覧(備忘録)

Posted at

React初心者のためのよく使う機能一覧

React初心者の方が最初に覚えておくと便利な機能をまとめました。徐々に理解を深めていくための一覧として参考にしてください。

1. コンポーネント作成

関数コンポーネント

function Greeting(props) {
  return <h1>こんにちは、{props.name}さん</h1>;
}

// 使用例
<Greeting name="田中" />

クラスコンポーネント(レガシーですが知っておくと良い)

class Greeting extends React.Component {
  render() {
    return <h1>こんにちは、{this.props.name}さん</h1>;
  }
}

2. React Hooks

useState - 状態管理

function Counter() {
  const [count, setCount] = React.useState(0);
  
  return (
    <div>
      <p>カウント: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        増やす
      </button>
    </div>
  );
}

useEffect - 副作用の処理

function DataFetcher() {
  const [data, setData] = React.useState(null);
  
  React.useEffect(() => {
    // マウント時に一度だけ実行
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // 空の依存配列
  
  return <div>{data ? JSON.stringify(data) : 'ローディング中...'}</div>;
}

useContext - コンテキストの利用

// コンテキストの作成
const ThemeContext = React.createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}

function ThemedButton() {
  const theme = React.useContext(ThemeContext);
  return <button className={theme}>テーマ付きボタン</button>;
}

3. イベント処理

function Button() {
  const handleClick = (e) => {
    e.preventDefault();
    console.log('クリックされました');
  };
  
  return <button onClick={handleClick}>クリック</button>;
}

4. 条件付きレンダリング

function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn 
        ? <h1>おかえりなさい!</h1> 
        : <h1>ログインしてください</h1>}
    </div>
  );
}

5. リストのレンダリング

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

6. フォーム処理

function SimpleForm() {
  const [input, setInput] = React.useState('');
  
  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`送信された値: ${input}`);
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <button type="submit">送信</button>
    </form>
  );
}

7. useRef - DOM要素の参照

function FocusInput() {
  const inputRef = React.useRef(null);
  
  const focusInput = () => {
    inputRef.current.focus();
  };
  
  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>入力欄にフォーカス</button>
    </>
  );
}

8. カスタムフック

// カスタムフック
function useWindowSize() {
  const [size, setSize] = React.useState({
    width: window.innerWidth,
    height: window.innerHeight
  });
  
  React.useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return size;
}

// 使用例
function WindowSizeDisplay() {
  const size = useWindowSize();
  return <p>ウィンドウサイズ: {size.width} x {size.height}</p>;
}

9. メモ化による最適化

React.memo - コンポーネントのメモ化

const MemoizedComponent = React.memo(function MyComponent(props) {
  // propsが変わらなければ再レンダリングしない
  return <div>{props.name}</div>;
});

useMemo - 値のメモ化

function ExpensiveCalculation({ a, b }) {
  const result = React.useMemo(() => {
    // 重い計算
    return a * b * 1000000000;
  }, [a, b]); // a または b が変わった時だけ再計算
  
  return <div>計算結果: {result}</div>;
}

10. ルーティング (React Router)

// React Routerのインストールが必要です
// npm install react-router-dom

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">ホーム</Link>
        <Link to="/about">概要</Link>
      </nav>
      
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

まとめ

Reactには多くの機能がありますが、上記の基本的な機能を理解するだけでも多くのアプリケーションを構築できます。Reactの公式ドキュメントもとても充実しているので、これらの概念を深く理解したい場合は参照してみてください。

初心者の方は、特に以下の概念を優先的に学ぶことをおすすめします:

  • コンポーネントの作成と再利用
  • useState と useEffect の使い方
  • イベント処理と条件付きレンダリング
  • リストの扱い方

これらを理解すれば、Reactアプリケーション開発の基礎が身につきます!

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?