Quickstart
note
This document gives a very brief overview of how Kea works. Please read Core Concepts to read not only what you can do in Kea, but also why. It's required reading if you are starting to use Kea in an actual app.
Another note
If you prefer to build a working app as you follow along, skim through this page to get a basic overview and then follow the Github API tutorial.
#
LogicAll Kea code lives inside a logic
, which is created by calling kea()
#
ActionsEvery operation in Kea start with an action:
Think of actions as events that are dispatched onto a queue. On their own they do nothing. Reducers and listeners (explained below) wait for actions and react accordingly.
Actions are functions that take whatever arguments you choose and return a payload
.
This payload should always be an object: (amount) => ({ amount })
.
You call actions in React through the useActions
hook:
Clicking this button dispatches an action with the payload { amount: 1000 }
#
ReducersReducers hold your state and modify it in response to actions:
To create a reducer, you provide it with a list of actions that modify its state (the keys of the object above) and how (the values of the same object).
Each change is described by a function that gets two arguments: the current state
of the reducer and the payload
of
the action that was dispatched.
Reducers must never mutate values. When dealing with complex objects, always create and return a new object that incorporates the required changes.
You are also not allowed to make API calls or dispatch actions inside a reducer.
To access the data stored in reducers from React, use the useValues
hook:
#
ListenersAll API calls and other side effects must happen inside listeners
.
Listeners and reducers can and should reuse actions whenever possible. That's why actions are defined separately.
For example you can add a isLoading
reducer that sets its state to true
when the loadUsers
action is dispatched
and to false
when setUsers
is dispatched after.
#
SelectorsSelectors combine reducers and other selectors into new pre-calculated values.
Each reducer has a selector made for it automatically, which you can use as input in new selectors:
Get the output of a selector in React with useValues
, just like with reducers:
Selectors are recalculated only when their input changes. They are perfect for memoizing complex operations.
Selectors are actually functions that take the redux store's current state
as an argument and return
whatever value you're looking for:
#
ValuesValues are a shorthand to access the current state of selectors.
You mostly use them in listeners to fetch some value:
This is where the hook useValues
gets its name.
Next Steps
- Ready to install Kea? Read the installation instructions!
- I strongly recommend you read Core Concepts to get a better understanding of why everything works the way it does.