@rbxts/roact-hooks
TypeScript icon, indicating that this package has built-in type declarations

0.5.1-ts.0 • Public • Published

Roact-Hooks-TS

A typescript port of the Roact-Hooks module. An implementation of React hooks for Roact.


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.

Dependencies (0)

    Dev Dependencies (3)

    Package Sidebar

    Install

    npm i @rbxts/roact-hooks

    Weekly Downloads

    7

    Version

    0.5.1-ts.0

    License

    MPL-2.0

    Unpacked Size

    44.4 kB

    Total Files

    14

    Last publish

    Collaborators

    • rimuy