Simple and powerful state using React context
constate
context + state = constate
Tiny React state management library that lets you work with local state and scale up to global state with ease when needed.
import React from "react";
import { Container } from "constate";
const initialState = { count: 0 };
const actions = {
increment: () => state => ({ count: state.count + 1 })
};
const Counter = () => (
<Container initialState={initialState} actions={actions}>
{({ count, increment }) => (
<button onClick={increment}>{count}</button>
)}
</Container>
);
});
On the other hand, [`effects`](#effects) and lifecycle methods can be a little tricky to test depending on how you implement them.
You can also use [`mount`](#mount) to create integration tests. This is how we can test our `CounterContainer` with its [`tick effect`](#effects):
```jsx
import { mount } from "constate";
import CounterContainer from "./CounterContainer";
test("initialState", () => {
const state = mount(CounterContainer);
expect(state.count).toBe(0);
});
test("increment", () => {
const state = mount(CounterContainer);
expect(state.count).toBe(0);
state.increment(1);
expect(state.count).toBe(1);
state.increment(-1);
expect(state.count).toBe(0);
});
test("getParity", () => {
const state = mount(<CounterContainer initialState={{ count: 1 }} />);
expect(state.getParity()).toBe("odd");
});
test("tick", () => {
jest.useFakeTimers();
const state = mount(CounterContainer);
state.tick();
jest.advanceTimersByTime(1000);
expect(state.count).toBe(1);
jest.advanceTimersByTime(1000);
expect(state.count).toBe(2);
});