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.

React HooksでStackな構造を扱うカスタムフック

0
Last updated at Posted at 2020-08-05

(2020.08.12更新)
こちらで公開しました。
https://github.com/nariakiiwatani/react-use-stack-ref
https://www.npmjs.com/package/react-use-stack-ref
少し修正加えてるのでもし使われる際はこちらを使ってください。

npm i react-use-stack-ref
または
yarn i react-use-stack-ref
でインストールできます。


useStackRef.ts

スタック構造を持ったデータをスッキリ扱いたかったので作った。
作ってみてわかったのは、これはもうほとんどArrayにスタックのインターフェースを被せただけものになったということ。
それでも使う側はだいぶスッキリするから、ないよりはあった方が良くはある。

useStackRef.ts
import { useRef } from "react";

export interface Stack<T> {
	value: T | null
	size: number
	push: (t: T) => number
	pop: () => T
	reset: () => void
	clear: () => void
}

export const useStackRef = <T>(init: T | T[] | (() => T) | (() => T[]) = []): Stack<T> => {
	const initial: T[] = ((value) => Array.isArray(value) ? value : [value])(init instanceof Function ? init() : init)
	const stackRef = useRef<T[]>(initial)

	const push = (t: T): number => stackRef.current.push(t)
	const pop = (): T => stackRef.current.pop() || null
	const reset = (): void => { stackRef.current = initial }
	const clear = (): void => { stackRef.current = [] }

	return {
		value: stackRef.current.slice(-1)[0] || null,
		size: stackRef.current.length,
		push, pop, reset, clear
	};
};

ちなみに、useRefでなくuseStateのスタックを作って紹介している記事はこちら。
React Hooksのカスタムフックが実現する世界 - オブジェクト指向とOSS

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?