Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 898

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T03:09:07+00:00 2024-11-25T03:09:07+00:00

React Hooks Factories

  • 62k

Factory pattern with React Hooks is not mentioned often enough however, it is often used in popular libraries to push composition to its limits.

It can also be used to simplify, in some cases optimise, sharing state across the React app.

Factory Pattern Crash Course

Factory pattern is used to bring an ability to create objects on the runtime.

It usually looks like this. Bear in mind that these are simple examples to paint a picture.

interface User {   name: string }  class Factory {   public static getUser(name: string): User {     return { name }   } }  const user = Factory.getUser("Bob") // { name: "Bob" }  // Alternatively, without classes  function getUser(name: string): User {   return { name } }  const user = getUser("Bob") // { name: "Bob" } 
Enter fullscreen mode Exit fullscreen mode

First Hook Factory

It will be a custom hook wrapping useState but it will set a default value provided at the time of creation.

// Factory function that returns a new function that uses Hooks API. function createHook(initialValue: string) {   return function useHook() {     return React.useState(initialValue)   } }  // Create the hook. const useHook = createHook("some initial value")  // Use the hook in the component. // The component will output: "State is: some initial value" function Component() {   const [state] = useHook()   return (     <>       State is: <b>{state}</b>     </>   ) } 
Enter fullscreen mode Exit fullscreen mode

Hook Factory With Custom Logic

Factories unlock the next level of composition.
For example, a factory can produce a hook that can be given custom logic at the time of creation.

// Factory function that returns a new function that uses Hooks API. function createMappedState(mapper: (value: string) => string) {   return function useHook(initialValue: string) {     const [state, setState] = React.useState(mapper(initialValue))      // Define a custom setter applying custom logic.     const setter = React.useCallback(       (value: string) => {         setState(mapper(value))       },       [setState]     )      // return a tuple to make API similar to React.useState     return [state, setter]   } }  // You can create as many custom hooks you need const useUppercasedString = createMappedState(value => value.toUpperCase()) const useLowercasedString = createMappedState(value => value.toLowerCase())  // Use the hook in the component. // The component will output: // ` // String is: SOME VALUE // String is: some value // ` function Component() {   const [string1, setString1] = useUppercasedString("Some Value")   const [string2, setString2] = useLowercasedString("Some Value")   return (     <>       String1 is: <b>{string1}</b>       <br />       String2 is: <b>{string2}</b>     </>   ) } 
Enter fullscreen mode Exit fullscreen mode

Sharing state across hooks to create context without Context API

Factories get interesting when you realize that the new function has access to the scope of the factory.

function createSharedStateHook(initialValue: string) {   let sharedValue = initialValue    // An array in a shared scope.   // Produced hook will always refer to it.   const stateSetters: ((v: string) => void)[] = []    // This function will update all components   // that use the hook created by the factory.   function setAllStates(value: string) {     sharedValue = value     stateSetters.forEach(set => {       set(value)     })   }    return function useSharedState(): [string, (v: string) => void] {     const [state, setState] = React.useState(sharedValue)      React.useEffect(() => {       // On mount, add the setter to shared array.       const length = stateSetters.push(setState)       const index = length - 1       return () => {         // On unmount, remove the setter.         stateSetters.splice(index, 1)       }     }, [setState])      // The trick is to have the hook to return the same instance of `setAllStates`     // at all times so the update will propagate through all components using the produced hook.     return [state, setAllStates]   } }  const useSharedState = createSharedStateHook("initial") const useAnotherSharedState = createSharedStateHook("another initial")  // `useSharedState` and `useAnotherSharedState` do not share the same state // because returned hooks have access to different scopes.  function Component() {   const [sharedState] = useSharedState()   return (     <>       Shared state is: <b>{sharedState}</b>     </>   ) }  function AnotherComponent() {   const [sharedState] = useAnotherSharedState()   return (     <>       Another shared state is: <b>{sharedState}</b>     </>   ) }  function Modifier() {   const [sharedState, setSharedState] = useSharedState()   return (     <input       type="text"       value={sharedState}       onChange={e => setSharedState(e.target.value)}     />   ) }  function App() {   return (     <>       <Component />       <br />       <AnotherComponent />       <br />       <Component />       <br />       <Modifier />     </>   ) } 
Enter fullscreen mode Exit fullscreen mode

Now, this hook provides a shared state without having to wrap an app with a Context Provider.

Not having to wrap a large section of the tree brings an alternative way to optimise re-renders without having to resort to more advanced APIs.

Who Is Using This Pattern?

Material-UI's makeStyles function allows to create styles for specific components.

use-local-storage-state – the prime example that inspired me to write this blog post.

In Conclusion

React Hooks are a great way to compose functionality in the ecosystem. Adding a factory pattern on top of it opens the door to more interesting ways to solve problems beyond stitching hooks together.

architecturejavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.