1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】孫コンポーネントや子コンポーネントに値や関数を渡していく【バケツリレー地獄の終焉】

Posted at

コンポーネントのバケツリレー地獄を過去にしたい

下記のように何度もpropを渡していく。。。
そんなのもう、やめにしませんか?

import React, {Fragment} from "react";

//親
export const Hoge= () => {
  const prop= "NEKO";
return (
  <Fragment>
     <Fuga prop={porp} />
  <Fragment>
)
}
//子供
export const Fuga =(prop) => {
    return(
     <Fragment>
         <Piyo prop={porp} />
      <Fragment>
    )
}
//孫
export const Piyo = (prop) => {
    return(
     <Fragment>
         <Puyo prop={porp} />
      <Fragment>
)
}

バケツリレーからの解放

下記のように親と孫でコードを加えて、その間のコンポーネントでpropの受け渡しを書かないようにしていきましょう。
reacr
import React, {Fragment,createContext,} from "react";

//親
export const Hoge= () => {
  //createContextで渡したい値の設定をします
  const state = createContext("NEKO");
  const dispatch = createContext("DISPATCHNEKO");

return (
  <Fragment>
   //ここで先ほど代入した変数のProviderで渡したい下のコンポーネントを囲みます
   <dispatch.Provider value={dispatch}>
        <state.Provider value={state}> 
           <Fuga />
          </state.Provider>
       </cispatch.Provider>
  <Fragment>
)
}
//子供(なにもしない)
export const Fuga =() => {
    return(
     <Fragment>
         <Piyo />
      <Fragment>
    )
}

//孫
export const Piyo = () => {
//使用したいコンポーネントでuseContextを使って値を受け取ります
const cescriptionState = useContext(state);
const cescriptionDispatch = useContext(cispatch);
    return(
     <Fragment>
         <Puyo />
         {state}
         {dispacth}
      <Fragment>
)
}

参考

https://qiita.com/ryokkkke/items/dc25111fcf52ea579d58
1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?