0
0

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 5 years have passed since last update.

useStateをまとめて書きたい

0
Last updated at Posted at 2020-09-01

useStateを1行でまとめて書きたい

useContextやuseStateなどのHooksを何度も使う場合に、省略する方法を考えました。
個人的にちょっと便利です。

useSomeHooks.js
export const useSomeStates = (useState, initialValues=[]) => initialValues.map(useState)
export const useSomeContexts = (useContext, stores=[]) => stores.map(useContext)
index.js
import React, {useState, useContext} from "react"
import {useSomeStates, useSomeContexts} from "./useSomeHooks.js"

// in your components
const [[name, setName], [age, setAge], [isHandsome, setIsHandsome]] = useSomeStates(useState, ["", 0, false])

const [{state: {tasks}}, {state: {user}}] = useSomeContexts(useContext, [taskStore, userStore])

より良い方法があれば教えて下さい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?