Using with React
Kea supports both, function
and Class
components.
#
Functional ComponentsYou use hooks to fetch actions and values from your logic. Here are the two most common Hooks. See the Hooks API reference for two more!
When you use a Hook, Kea makes sure the logic is mounted as your component renders and gets automatically unmounted when your component is removed from React.
useActions
#
Fetch actions from a logic.
useValues
#
Fetch values from a logic.
note
Please Note! You can only use useValues
with destructoring:
This is because internally useValues
uses getter functions
that call react-redux's useSelector
hooks when a value is accessed. Because hooks need to always be called in the same order,
you can't just store the object returned from useValues
and then use its properties later in
the code. Doing so might call the internal hooks in an unspecified order. Use
useAllValues
if you need to do this.
#
Class Componentslogic(Component)
#
If you wrap your Component
inside a logic
, it'll get all the values
and actions
as props.
connect
#
In case you don't want to hook up everything in a logic
to your Component
or if you
want to mix and match values from multiple logics, use kea({ connect: { ... } })
as discussed in
the explicit connections section under Additional Concepts,
to create a new logic with only the actions and values you need. Then wrap your Component
in that.
If you go for this route, you can use a small helper function called connect
, which is literally just:
You use it like so:
In case you don't fear experimental JS syntax, you can use legacy decorators and simplify your code down a bit:
#
BindLogicWhen using a keyed logic, such as this itemLogic
:
you might end up in a nested hierarchy such as this:
Redux (that Kea is built on) was supposed to save us from passing down props everywhere, so this is a bummer. Until Kea 2.3 you only had three options in this case:
- Pass around the
id
like above. - Pass along the entire
item
. This works if it's just one thing and a few components to pass it to. If your children also need access to some actions and other values fromitemLogic({ id })
, you're in for a mess. - Pass along the
const logic = itemLogic({ id })
as<ItemTitle logic={logic} />
so the children can just useuseValues(logic)
. Clunky, but at least straightforward.
Starting with Kea 2.3 you can use the tag <BindLogic />
:
Thus you can just write:
Using <BindLogic />
, Kea stores the built logic itemLogic({ id })
inside a React Context.
All child components that call useValues(itemLogic)
will get that specific mounted instance of the logic.
Next steps
- Using TypeScript? Read how it works with Kea!
- Read about Debugging to be even more productive when working with Kea!
:::