npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@rbxts/roact-hooks

v0.5.1-ts.0

Published

Typings for Kampfkarren's roact-hooks module

Downloads

69

Readme

Intro to hooks

For the constructor, you should pass in the Roact you are using, since can't combine multiple versions of Roact together.

Returns a function that can be used to create a new Roact component with hooks. An optional object can be passed in. The following are the valid keys that can be used, and what they do.

name

Refers to the name used in debugging. If it is not passed, it'll use the function name of what was passed in.

componentType

Defines if the component will be either a Component or a PureComponent.

validateProps

Provides a mechanism for verifying inputs passed into the component.

Example

ClickCounter.tsx

import Roact from "@rbxts/roact";
import Hooks from "@rbxts/roact-hooks";

const ClickCounter: Hooks.FC = (_props, { useState }) => {
	const [counter, setCounter] = useState(0);

	return (
		<textbutton
			Text={tostring(counter)}
			TextSize={18}
			Position={new UDim2(0.5, -100, 0.5, -25)}
			Size={UDim2.fromOffset(200, 50)}
			Event={{ MouseButton1Click: () => setCounter(counter + 1) }}
		/>
	);
};

export = new Hooks(Roact)(ClickCounter);

Props & Default Props Example

PrintsOnClick.tsx

interface Props {
	buttonText: string;
	printMessage: string;
}

const PrintsOnClick: Hooks.FC<Props> = (props, { useCallback }) => {
	const doPrint = useCallback(() => {
		print(props.printMessage);
	});

	return (
		<textbutton
			Size={UDim2.fromScale(0.5, 0.5)}
			Text={props.buttonText}
			Event={{ Activated: () => doPrint() }}
		/>
	);
};

export = new Hooks(Roact)(PrintsOnClick, {
	defaultProps: {
		buttonText: "Click me...",
		printMessage: "it was clicked!"
	}
});

Reducer Example

An alternative to useState that uses a reducer rather than state directly. If you’re familiar with Rodux, you already know how this works.

Stepper.tsx

interface State {
	count: number;
}

const enum Actions {
        INCREMENT = "increment",
        DECREMENT = "decrement",
}

const initialState: State = {
        count: 0,
};

const reducer: Hooks.Reducer<State, Hooks.Action<Actions>> = (state, action) => {
        switch(action.type) {
                case Actions.INCREMENT:
                        return {
                                count: state.count + 1,
                        };
                case Actions.DECREMENT:
                        return {
                                count: state.count - 1,
                        };
        }
};

const Stepper: Hooks.FC = (_props, { useReducer }) => {
        const [state, dispatch] = useReducer(reducer, initialState);

        return (
                <frame
                        BackgroundTransparency={1}
                        Size={UDim2.fromScale(1, 1)}
                >
                        <uilistlayout
                                Key="UIListLayout"
                                FillDirection={Enum.FillDirection.Vertical}
                                Padding={new UDim(0, 5)}
                                SortOrder={Enum.SortOrder.LayoutOrder}
                        />
                        <textlabel
                                Key="Counters"
                                BackgroundTransparency={1}
                                Font={Enum.Font.Code}
                                LayoutOrder = {1}
                                Size={new UDim2(1, 0, 0, 38)}
                                Text={tostring(state.count)}
                                TextColor3={new Color3(0, 1, 0)}
                                TextSize={32}
                        />
                        <textbutton
                                Key="Increment"
                                BackgroundColor3={new Color3(0, 1, 0)}
                                Font={Enum.Font.Code}
                                LayoutOrder={2}
                                Size={new UDim2(1, 0, 0, 38)}
                                Text="Increment"
                                TextColor3={new Color3(1, 1, 1)}
                                TextScaled
                                Event={{
                                        Activated: () => {
                                                dispatch({
                                                        type: Actions.INCREMENT,
                                                })
                                        }
                                }}
                        />
                        <textbutton
                                Key="Decrement"
                                BackgroundColor3={new Color3(1, 0, 0)}
                                Font={Enum.Font.Code}
                                LayoutOrder={3}
                                Size={new UDim2(1, 0, 0, 38)}
                                Text="Decrement"
                                TextColor3={new Color3(1, 1, 1)}
                                TextScaled
                                Event={{
                                        Activated: () => {
                                                dispatch({
                                                        type: Actions.DECREMENT,
                                                })
                                        }
                                }}
                        />
                </frame>
        );
};

export = new Hooks(Roact)(Stepper);

Creating a hook

To create a custom hook all you need to do is to create a function, with its name starting with use. It may as well call other hooks.

Example

hooks.ts

import ChatAPI, { Status } from "Server/ChatAPI";

export const useFriendStatus = (
        friendID: number,
        { useState, useEffect }: CoreHooks
) => {
        const [isOnline, setIsOnline] = useState(false);

        useEffect(() => {
                const handleStatusChange = (status: Status) => {
                        setIsOnline(status.isOnline);
                }

                ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
                return () => {
                        ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
                };
        });

        return isOnline;
};

FriendListItem.tsx

import { useFriendStatus } from "./hooks.ts";

export interface FriendListItemProps {
        name: string;
        id: number;
}

const FriendListItem: Hooks.FC<FriendListItemProps> = (props, hooks) => {
        const isOnline = useFriendStatus(props.id, hooks);

        return (
                <frame
                        Key={props.name}
                        Size={UDim2.fromOffset(320, 70)}
                >
                        <textlabel
                                Key="Username"
                                BackgroundTransparency={1}
                                Size={new UDim2(1, -10, 1, 0)}
                                Text={props.name}
                                TextSize={14}
                        />
                        <frame
                                Key="Status"
                                BackgroundColor3={
                                        isOnline 
                                                ? Color3.fromRGB(0, 191, 3)
                                                : Color3.fromRGB(100, 100, 100)
                                }
                                BorderSizePixel={0}
                                Position={new UDim2(1, -10, 0, 0)}
                                Size={new UDim2(0, 10, 1, 0)}
                        />
                </frame>
        );
}

export default new Hooks(Roact)(FriendListItem);

To get more in depth on how this works, check the original library's repository.

Extra

Using a default property

The defaultProps property is intentionally excluded from the Hooks class because TypeScript already have a shorthand syntax for assigning default properties. This can be achieved by destructuring your props object and using = to assign a default value to the chosen property.

interface Props {
        hello: string;
        world?: string;
}

const HelloWorld: Hooks.FC<Props> = (({ hello, world = ", World!" }, hooks) => {
        return <textlabel Text={hello + world} />
});

export = new Hooks(Roact)(HelloWorld);

<HelloWorld hello="Hello" /> // Text will be "Hello, World!"

Re-using a hooked component factory

The Hooks class doesn't necessarily need to be created for each new component, instead it can be stored in a variable and exported to be used by the components.

export const hooks = new Hooks(Roact);
// Some of the ViewportFrame props
interface ComponentProps {
        ImageTransparency?: number;
        LightDirection?: Vector3;
}

export const Viewport = hooks((props: ComponentProps, hooks) => {
        return <viewportframe {...props} />;
});

// Or:
export const Viewport2 = hooks<ComponentProps>((props, hooks) => {
	return <viewportframe {...props} />;
});

License

This library is licensed under the MPL-2.0 License. The original Roact-Hooks library's License can be found here.