{"componentChunkName":"component---node-modules-gatsby-theme-blog-core-src-templates-post-query-js","path":"/react-instant-hook/","result":{"data":{"site":{"siteMetadata":{"title":"L3F7 - a work in progress","social":[{"name":"twitter","url":"https://twitter.com/liamptfarrelly"},{"name":"github","url":"https://github.com/lfarrel6"}]}},"blogPost":{"__typename":"MdxBlogPost","id":"d3f45ace-4dd2-5adc-89cf-7abdd076d25f","excerpt":"I use contexts a decent amount in react, and I typically write custom hooks for them. The hooks are largely boilerplate, taking the form of…","body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Custom context hooks in react\",\n  \"date\": \"2020-05-04T00:00:00.000Z\"\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"p\", null, \"I use contexts a decent amount in react, and I typically write custom hooks for them. The hooks are largely boilerplate, taking the form of: \"), mdx(\"ul\", null, mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"useContext\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"check the value\"), mdx(\"li\", {\n    parentName: \"ul\"\n  }, \"return the value or throw an Error.\")), mdx(\"p\", null, \"I released \", mdx(\"a\", _extends({\n    parentName: \"p\"\n  }, {\n    \"href\": \"https://npmjs.com/package/react-instant-hook\"\n  }), \"react-instant-hook\"), \" to remove all of that boilerplate and to make custom hooks more convenient.\\nIt\\u2019s pretty simple (less than 40 lines) and allows you to make custom hooks for your contexts with a single function call.\"), mdx(\"p\", null, \"I got the idea for this library while reading \", mdx(\"a\", _extends({\n    parentName: \"p\"\n  }, {\n    \"href\": \"https://kentcdodds.com/blog/how-to-use-react-context-effectively\"\n  }), \"\\u2018How to use React context effectively\\u2019\"), \" by Kent C. Dodds.\\nIt\\u2019s a great read on context best practices.\"), mdx(\"p\", null, \"This post isn\\u2019t going to go explain contexts, or when to use them, I think Kent\\u2019s post sums that up really well. This will simply serve as a brief introduction to the module and how to use it.\"), mdx(\"h2\", {\n    \"id\": \"using-react-instant-hook\"\n  }, \"Using react-instant-hook\"), mdx(\"p\", null, \"Taking the example from Kent\\u2019s blog post\\u2026\"), mdx(\"pre\", null, mdx(\"code\", _extends({\n    parentName: \"pre\"\n  }, {\n    \"className\": \"language-jsx\"\n  }), \"/**\\n * Adapted from\\n * https://kentcdodds.com/blog/how-to-use-react-context-effectively\\n **/\\nimport React from 'react';\\nimport { getHook } from 'react-instant-hook';\\n\\nconst CountStateContext = React.createContext();\\nconst CountDispatchContext = React.createContext();\\n\\nfunction countReducer(state, action) { ... }\\n\\nfunction CountProvider({children}) {\\n  const [state, dispatch] = React.useReducer(countReducer, {count: 0})\\n  return (\\n    <CountStateContext.Provider value={state}>\\n      <CountDispatchContext.Provider value={dispatch}>\\n        {children}\\n      </CountDispatchContext.Provider>\\n    </CountStateContext.Provider>\\n  )\\n}\\n\")), mdx(\"p\", null, \"We establish two contexts, a reducer and a provider component.\\nUsing \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"react-instant-hook\"), \", we can create the custom hooks for our contexts in just 3 lines!\"), mdx(\"pre\", null, mdx(\"code\", _extends({\n    parentName: \"pre\"\n  }, {\n    \"className\": \"language-js\"\n  }), \"const useCountState = getHook(CountStateContext);\\nconst useCountDispatch = getHook(CountDispatchContext);\\nconst useCount = getHook([CountStateContext,CountDispatchContext]);\\n\")), mdx(\"p\", null, mdx(\"em\", {\n    parentName: \"p\"\n  }, \"As an aside, I really like this pattern of isolating the concerns of your contexts.\"), \" Less unused variables, and clearer code - it\\u2019s a win-win! \\uD83D\\uDE80\"), mdx(\"p\", null, \"For the most part the module is unopinionated, with the exception of validating the value returned by the context. You shouldn\\u2019t be using hooks outside of their corresponding providers, so it\\u2019s better that the hooks fail fast than fail silently.\"), mdx(\"p\", null, \"By default, \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"react-instant-hook\"), \" validates that the value returned from the context is not undefined. This can be overwritten with an optional secondary parameter.\"), mdx(\"pre\", null, mdx(\"code\", _extends({\n    parentName: \"pre\"\n  }, {\n    \"className\": \"language-js\"\n  }), \"// Default validation - let's just make sure the value isn't undefined\\nconst validateValue = (value) => value !== undefined; \\n\")), mdx(\"p\", null, \"If this validation fails, \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"react-instant-hook\"), \" will throw an error. If you want to go rogue and use your hook without any validation, pass \", mdx(\"inlineCode\", {\n    parentName: \"p\"\n  }, \"() => true\"), \" as the second parameter.\\nNot pretty, but neither is using a context consumer outside of the provider!\"), mdx(\"p\", null, \"If you have any questions or suggestions, you can \", mdx(\"a\", _extends({\n    parentName: \"p\"\n  }, {\n    \"href\": \"https://twitter.com/liamptfarrelly\"\n  }), \"tweet me\"), \" or leave an issue in the \", mdx(\"a\", _extends({\n    parentName: \"p\"\n  }, {\n    \"href\": \"https://github.com/lfarrel6/react-instant-hook\"\n  }), \"github repo\"), \".\"));\n}\n;\nMDXContent.isMDXComponent = true;","slug":"/react-instant-hook/","title":"Custom context hooks in react","tags":[],"keywords":[],"date":"May 04, 2020"},"previous":null,"next":null},"pageContext":{"id":"d3f45ace-4dd2-5adc-89cf-7abdd076d25f"}}}