Search code examples
javascripttypescriptfunctional-programmingcomponentspurely-functional

Can a functional component be considered as pure if it has an internal mutable state?


Let's consider a functional component that has a mutable internal state:

const FComponent = (options: any)  => {
     let privateID = '0000';

     return {
          ...{ // Public fields
               name: 'component'
          },
          ...{ // Public methods
               setPrivateID: (id: string) => {
                    privateID = id;
               }
          }
     }
};

FComponent({}).setPrivateID('0001');

Should I rather return a new component that has the requested ID ?

Something like this ? A Functor I suppose ? https://medium.com/javascript-scene/functors-categories-61e031bac53f

const FComponent = (options: {id: string})  => {
     return {
          ...{
               name: 'component'
          },
          ...{
               privateID: (id: string) => {
                    return FComponent({id})
               }
          }
     }
};


Solution

  • A function that mutates state isn't pure since mutating state is a side effect.

    The second version does not mutate state but creates a new object. This is how the String class in Java works, which is purely functional.