1.0.0 • Published 7 years ago

fn-key-cache v1.0.0

Weekly downloads
34
License
MIT
Repository
github
Last release
7 years ago

fn-key-cache

NPM version Build status Test coverage Dependency Status License Downloads

Little utility to cache functions based on keys. Useful for creating handlers in React:

import React, { Component } from 'react'

import KeyCache from 'fn-key-cache'

export default class Thing extends Component {
  state = {
    tab: 1
  }

  onClickButton = KeyCache(tab => e => {
    e.preventDefault()

    this.setState({
      tab
    })
  })

  render () {
    const { tab } = this.state

    return (
      <div className='container'>
        <button type='button' className={tab === 1 ? 'active' : ''} onClick={this.onClickButton(1)}>1</button>
        <button type='button' className={tab === 2 ? 'active' : ''} onClick={this.onClickButton(2)}>2</button>
        <button type='button' className={tab === 3 ? 'active' : ''} onClick={this.onClickButton(3)}>3</button>
      </div>
    )
  }
}

Without this utility, new functions would be created on every render().