LoginSignup
3
2

More than 3 years have passed since last update.

【react hooks】useContextを使ってみた

Posted at

hooksのuseContextを使ってみる

めちゃ簡単なカウンター作ってみた。
https://codesandbox.io/s/condescending-turing-6gtgf

ソース

import React, { useState, useContext, createContext, useCallback } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Counter = createContext();

function App() {
  const [count, setCount] = useState(0);
  const increment = useCallback(() => setCount(count + 1), [count]);
  const decrement = useCallback(() => {
    if (count > 0) setCount(count - 1);
  }, [count]);
  return (
    <div className="App">
      <Counter.Provider
        value={{
          count,
          increment,
          decrement
        }}
      >
        <Child />
      </Counter.Provider>
    </div>
  );
}

const Child = () => {
  const { count, increment, decrement } = useContext(Counter);
  return (
    <>
      {count}
      <button onClick={increment}>increment</button>
      <button onClick={decrement}>decrement</button>
    </>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

これで簡単にバケツリレー回避できるんだね。
createContextについて全然知らなくてhooks触ってて気がついた。
これから使っていってみよう。

3
2
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
2