Skip to content

Commit

Permalink
update(react-hooks): global store hook (useStore)
Browse files Browse the repository at this point in the history
issue #105
  • Loading branch information
sabertazimi committed Nov 11, 2018
1 parent 0328589 commit b5de58a
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions programming/web/reactjs/reactjsBasicNotes.md
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,34 @@ function usePrevious(value) {
}
```

```js
import { useState } from 'react';

export const store = {
state: {},
setState(value) {
this.state = value;
this.setters.forEach(setter => setter(this.state));
},
setters: []
};

// Bind the setState function to the store object so
// we don't lose context when calling it elsewhere
store.setState = store.setState.bind(store);

// this is the custom hook we'll call on components.
export function useStore() {
const [ state, set ] = useState(store.state);

if (!store.setters.includes(set)) {
store.setters.push(set);
}

return [ state, store.setState ];
}
```

## ES6 Syntax

### this.setState()
Expand Down

0 comments on commit b5de58a

Please sign in to comment.