jonathanong / fn-key-cache

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

fn-key-cache

NPM version Build status Test coverage Dependency Status Greenkeeper badge 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(). This is better than doing something like onClick={e => this.setState({ tab: 1 })}, but not better than just creating a new component.

About

License:MIT License


Languages

Language:JavaScript 100.0%