/  Technology   /  React Mixins
React Mixins

React Mixins

 

How do we share the code between components?

Component composition has always been the answer of sharing code between components. 

 It’s not always a certain pattern can be solved with configuration. React is determine by functional programming but it came into the field that was command by object-oriented libraries. It is hard for engineers both  outside  and inside of Facebook to give up on the patterns they happen used to.

To ease the initial adoption and learning, The react developers  included certain escape hatches into React. The React  mixin system was one of those escape hatches, and its goal was to give you a way to reuse code between components when you aren’t sure how to solve the same problem with composition.

Mixins is used in class components of React.

Example of a Mixin: 

import React from 'react';
var MyMixin = {
  doSomething(
  }
};
const MyComponent = React.createClass({
  mixins: [MyMixin],
  handleClick() {
    this.doSomething(); // invoke mixin's method
  },
  render() {
    return (
      <button onClick={this.handleClick}>Do Something</button>
    );
  }
});
export default MyComponent;

In the above code we are declaring a mixin and passing doSomething() function to it. The mixin is then used in the Component using the React.createClass method. The handle Click function accesses the and invokes the mixin method by using this.doSmothing(). A button is then rendered on the UI which calls this.handleClcik() function when the button is clicked.

Common  issues faced while using a Mixin method.

Dependencies

Sometimes, react mixins may depends on other mixins, whence dependency graph becomes unreadable.

Mixins disallow refactoring a state key and/or a method by searching for its occurrences in the component file.

Clashes in Names

The handleChange() is a typical method name for a functional components. React Mixins, by their nature, invoke methods in the same namespace, hence collisions are not uncommon.

If a name conflict with a react mixin come from a third party package, one solution is to refactor to often unreadable names to avoid clashes.

 Snowballing Complexity

Whenever a simple react mixin is generate, oftentimes it’ll become heavily furnished to serve components needs.

Each and every new requirement and feature imposed upon a mixin makes it harder to understand.

There is not a way to extract only needed piece(component) of code from a react mixin.

Thus, alternative method to mixins are being used such as Higher order components .

 

Leave a comment