loading...

Laco hooks api and code sandbox examples

deam profile image Deam ・2 min read

Laco is a simple and powerful state management solution for React. Powered by ideas from Redux and Unstated. For a short introduction to Laco please check out my previous post.

React just released a "minor" version (v16.8.0) which includes the long awaited hooks api. I personally think that the hooks api is a lot cleaner to write and I would recommend looking into it. Here's the official changelog blogpost for a good and brief overview.

Using Laco with with a render prop approach (the old way):

import { Store } from 'laco'
import { Subscribe } from 'laco-react'

// Creating a new store with an initial state { count: 0 }
const CounterStore = new Store({ count: 0 })

// Implementing some actions to update the store
const increment = () => CounterStore.set((state) => ({ count: state.count + 1 }))
const decrement = () => CounterStore.set((state) => ({ count: state.count - 1 }))

const Counter = () => (
  <Subscribe to={[CounterStore]}>
    {(state) => (
      <div>
        <button onClick={decrement}>-</button>
        <span>{state.count}</span>
        <button onClick={increment}>+</button>
      </div>
    )}
  </Subscribe>
)

Using Laco with the new and shiny hooks api:

import { Store } from 'laco'
import { useStore } from 'laco-react'

// Creating a new store with an initial state { count: 0 }
const CounterStore = new Store({ count: 0 })

// Implementing some actions to update the store
const increment = () => CounterStore.set(state => ({ count: state.count + 1 }))
const decrement = () => CounterStore.set(state => ({ count: state.count - 1 }))

const Counter = () => {
  const state = useStore(CounterStore) // Takes a single store
  return (
    <div>
      <button onClick={decrement}>-</button>
      <span>{state.count}</span>
      <button onClick={increment}>+</button>
    </div>
  )
}

useStore takes a single store but you can also import useStores which takes an array of stores. An example of useStores can be seen below.

import { Store } from 'laco'
import { useStores } from 'laco-react'

const CounterStore = new Store({ count: 0 })
const AnotherStore = new Store({ test: "hello" })

const Counter = () => {
  const [counterState, anotherState] = useStores([CounterStore, AnotherStore])
  return <div>{anotherState.test + counterState.count}</div>
}

Code sandbox examples

Code sandboxes using hooks:

Code sandboxes using render props:

Conclusion

I think the new hooks api is way better compared to the render props way of doing things since in render props you need to wrap a "Subscribe" component around your children which is a bit convoluted. Hooks api in this case is easier to read.

Discussion

pic
Editor guide