• Stars
    star
    3,916
  • Rank 10,717 (Top 0.3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React Context + State

constate logo

Constate

NPM version NPM downloads Size Dependencies GitHub Workflow Status (branch) Coverage Status

Write local state using React Hooks and lift it up to React Context only when needed with minimum effort.


🕹 CodeSandbox demos 🕹
Counter I18n Theming TypeScript Wizard Form

Basic example

import React, { useState } from "react";
import constate from "constate";

// 1️⃣ Create a custom hook as usual
function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(prevCount => prevCount + 1);
  return { count, increment };
}

// 2️⃣ Wrap your hook with the constate factory
const [CounterProvider, useCounterContext] = constate(useCounter);

function Button() {
  // 3️⃣ Use context instead of custom hook
  const { increment } = useCounterContext();
  return <button onClick={increment}>+</button>;
}

function Count() {
  // 4️⃣ Use context in other components
  const { count } = useCounterContext();
  return <span>{count}</span>;
}

function App() {
  // 5️⃣ Wrap your components with Provider
  return (
    <CounterProvider>
      <Count />
      <Button />
    </CounterProvider>
  );
}

Learn more

Advanced example

import React, { useState, useCallback } from "react";
import constate from "constate";

// 1️⃣ Create a custom hook that receives props
function useCounter({ initialCount = 0 }) {
  const [count, setCount] = useState(initialCount);
  // 2️⃣ Wrap your updaters with useCallback or use dispatch from useReducer
  const increment = useCallback(() => setCount(prev => prev + 1), []);
  return { count, increment };
}

// 3️⃣ Wrap your hook with the constate factory splitting the values
const [CounterProvider, useCount, useIncrement] = constate(
  useCounter,
  value => value.count, // becomes useCount
  value => value.increment // becomes useIncrement
);

function Button() {
  // 4️⃣ Use the updater context that will never trigger a re-render
  const increment = useIncrement();
  return <button onClick={increment}>+</button>;
}

function Count() {
  // 5️⃣ Use the state context in other components
  const count = useCount();
  return <span>{count}</span>;
}

function App() {
  // 6️⃣ Wrap your components with Provider passing props to your hook
  return (
    <CounterProvider initialCount={10}>
      <Count />
      <Button />
    </CounterProvider>
  );
}

Learn more

Installation

npm:

npm i constate

Yarn:

yarn add constate

API

constate(useValue[, ...selectors])

Constate exports a single factory method. As parameters, it receives useValue and optional selector functions. It returns a tuple of [Provider, ...hooks].

useValue

It's any custom hook:

import { useState } from "react";
import constate from "constate";

const [CountProvider, useCountContext] = constate(() => {
  const [count] = useState(0);
  return count;
});

You can receive props in the custom hook function. They will be populated with <Provider />:

const [CountProvider, useCountContext] = constate(({ initialCount = 0 }) => {
  const [count] = useState(initialCount);
  return count;
});

function App() {
  return (
    <CountProvider initialCount={10}>
      ...
    </CountProvider>
  );
}

The API of the containerized hook returns the same value(s) as the original, as long as it is a descendant of the Provider:

function Count() {
  const count = useCountContext();
  console.log(count); // 10
}

selectors

Optionally, you can pass in one or more functions to split the custom hook value into multiple React Contexts. This is useful so you can avoid unnecessary re-renders on components that only depend on a part of the state.

A selector function receives the value returned by useValue and returns the value that will be held by that particular Context.

import React, { useState, useCallback } from "react";
import constate from "constate";

function useCounter() {
  const [count, setCount] = useState(0);
  // increment's reference identity will never change
  const increment = useCallback(() => setCount(prev => prev + 1), []);
  return { count, increment };
}

const [Provider, useCount, useIncrement] = constate(
  useCounter,
  value => value.count, // becomes useCount
  value => value.increment // becomes useIncrement
);

function Button() {
  // since increment never changes, this will never trigger a re-render
  const increment = useIncrement();
  return <button onClick={increment}>+</button>;
}

function Count() {
  const count = useCount();
  return <span>{count}</span>;
}

Contributing

If you find a bug, please create an issue providing instructions to reproduce it. It's always very appreciable if you find the time to fix it. In this case, please submit a PR.

If you're a beginner, it'll be a pleasure to help you contribute. You can start by reading the beginner's guide to contributing to a GitHub project.

When working on this codebase, please use yarn. Run yarn examples to run examples.

License

MIT © Diego Haz

More Repositories

1

arc

React starter kit based on Atomic Design
JavaScript
2,910
star
2

rest

REST API generator with Node.js, Express and Mongoose
JavaScript
1,778
star
3

generact

Generate React components by replicating your own
JavaScript
1,481
star
4

awesome-react-context

😎 A curated list of stuff related to the new React Context API
JavaScript
915
star
5

styled-tools

Useful interpolated functions for CSS-in-JS
JavaScript
805
star
6

schm

Composable schemas for JavaScript and Node.js
JavaScript
513
star
7

reuse

♻️ Reuse React components to create new ones
TypeScript
496
star
8

singel

Single Element Pattern
JavaScript
409
star
9

nod

Node.js module generator/boilerplate with Babel, Jest, Flow, Documentation and more
JavaScript
360
star
10

redux-saga-thunk

Dispatching an action handled by redux-saga returns promise
JavaScript
221
star
11

styled-theme

Extensible theming system for styled-components 💅
JavaScript
183
star
12

querymen

Querystring parser middleware for MongoDB, Express and Nodejs (MEN)
JavaScript
129
star
13

parse-prop-types

Parses React prop-types into a readable object
JavaScript
67
star
14

bodymen

Body parser middleware for MongoDB, Express and Nodejs (MEN)
JavaScript
48
star
15

redux-saga-social-login

Facebook/Google login implementation with redux-saga
JavaScript
25
star
16

list-react-files

List React component files inside a directory
JavaScript
24
star
17

mongoose-keywords

Mongoose plugin that generates a keywords path combining other paths values
JavaScript
22
star
18

redux-modules

A modular approach to better organize redux stuff (not another library)
JavaScript
21
star
19

generator-rest-example

A fully commented RESTful API example generated with generator-rest
JavaScript
18
star
20

styled-selector

Get static CSS(-in-JS) selectors from React components
TypeScript
17
star
21

coolors-to-hex

Get hexadecimal values from a coolors url
JavaScript
16
star
22

webpack-blocks-split-vendor

A webpack block that splits vendor javascript into separated bundle
JavaScript
15
star
23

webpack-blocks-happypack

A webpack block that adds happypack support to your webpack config
JavaScript
12
star
24

redux-form-submit

Adds an async submit action creator to redux-form
JavaScript
9
star
25

webpack-spawn-plugin

A webpack plugin that runs child_process.spawn within compilation
JavaScript
7
star
26

waterfall-grid

A Polymer wrapper element for waterfall.js, a 1KB Javascript library for Pinterest-like grids.
HTML
7
star
27

webpack-blocks-server-source-map

A webpack block that adds source map support to server bundle
JavaScript
5
star
28

yo

A Yeoman generator for generating next generation of Yeoman generators
JavaScript
5
star
29

webpack-assets-by-type-plugin

A webpack plugin that save assets by type
JavaScript
5
star
30

arc-universal-redux

Universal Redux version of ARc boilerplate
JavaScript
5
star
31

webpack-sort-chunks

Sorts webpack chunks by dependency
JavaScript
4
star
32

webpack-child-config-plugin

A webpack plugin that runs/watches another config
JavaScript
4
star
33

rest-api

REST API Boilerplate with Mongoose, Express and Nodejs
JavaScript
4
star
34

rich-param

An object with name and value which accepts pluggable methods as formatters or validators
JavaScript
3
star
35

reakit-code-lab

TypeScript
3
star
36

arc-fullstack

Fullstack version of ARc boilerplate
JavaScript
3
star
37

mongoose-create-unique

Mongoose plugin to create a document or return the existing one based on the unique index
JavaScript
3
star
38

divisa

A game about war and peace.
JavaScript
2
star
39

eyeport

Collection of useful methods to deal with element and viewports in DOM
JavaScript
2
star
40

alpha-bank

JavaScript
2
star
41

guild

Just a social network prototype made with jQuery
HTML
2
star
42

is-git-rev

Verify if a string is a git-rev hash
JavaScript
2
star
43

clone

JavaScript
1
star
44

radiotoca

A PHP web radio with Twitter integration
PHP
1
star
45

adjacente

Blog para disciplina Expansão dos Sentidos
JavaScript
1
star
46

diegohaz

1
star
47

hear-parse

JavaScript
1
star
48

hear-api

JavaScript
1
star
49

diegohaz.com

JavaScript
1
star