Custom Components with useState
Learn to build custom React components in Upstreet Agents, leveraging the useState hook for state management.
useState is a React Hook that lets you add a state variable to your component.
Explanation
- Enables state management in functional components.
- Updates the component's state and triggers a re-render.
Usecase
- Introducing state to a component
- Modifying state using the previous state as a reference
- Updating objects and arrays within the state
- Preventing the recreation of the initial state
- Resetting state by utilizing a unique key
- Preserving data from earlier renders
Step 1: Integrate useState with Upstreet agents to build a component that generate random names
-
Install the Upstreet SDK using
usdk create -
Navigate to the
agent.tsxfile. -
You will find a pre-built
MyAgentcomponent like that.
Step 2: Import dependencies and create NameRandomizer component
Call useState, Prompt and Action at the top level of your component to declare a state variable.
Now create a component named NameRandomizer and set your states using useState
Step 3: Modify the NameRandomizer component
Create a generateRandomName function below the states in which an array of names is present and the function loops through this array to select a random using
MATH.floor and MATH.random().
Give agent a customized Prompt
Render the current name and provide a button to generate new name. This button will render the new state
Define the Action of the agent
The final state of NameRandomizer look like this.
Step 4: Import NameRandomizer in the Agent Components
Step 5: Test the agent
Run usdk chat in the terminal to test the agent.
You can ask agent
I want to guess random names!
