Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
2
Help us understand the problem. What is going on with this article?
@takujiro_0529

【react hooks】useContextを使ってみた

More than 1 year has passed since last update.

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触ってて気がついた。
これから使っていってみよう。

2
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
aircloset
「新しい当たり前を作る」を作ることをミッションに、airClosetを開発・運営しています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
2
Help us understand the problem. What is going on with this article?