How do I store data in a component?

Using the Roact library, how am I supposed to store data inside of a Component so that this data can be accessed by areas in my code other than from inside of my component? Also, is there a way to store functions? (If you are familiar with OOP terminology, how can I store “methods” and “attributes” inside of my components? Thanks.)

To ensure the XY problem doesn’t happen, I’m trying to give components higher up in the tree access to call the updating function of a Binding.

Thanks.

1 Like

I didn’t quite understand what you mean. If you want to store functions and data and not define them in every script, you use a module script to do so. There are a lot of tutorials on module scripts on youtube which show you how to use them.

No, what I’m saying is specific to the Roact library. I want to be able to store data in my Roact component and access it from higher up my tree.

It would help if you had a specific example of what you’re looking to accomplish. In general though, state that can be shared outside of the context of your Roact tree involves the use of Rodux with RoactRodux to connect the two. This allows you to setup a central “store” where all your state exists, which can be accessed by your Roact tree, and changed from external scripts.

To share state from one component to another, that’s a lot easier and does not need any extra libraries. Context is a great way to share around global state that you have (like the current theme, different visibility states, etc.)

For attaching custom functions to a component, a pretty common pattern is to add them to your init lifecycle hook. For example:

local Example = Roact.Component:extend("Example")

function Example:init()
    self.onActivated = function()
        print("Hello world!")
    end
end

function Example:render()
    return Roact.createElement("TextButton", {
        Text = "Click Me",
        -- ...
        [Roact.Event.Activated] = self.onActivated
    })
end
2 Likes