LoginSignup
12
14

More than 5 years have passed since last update.

React と jQuery は共存可能なのか?

Posted at

jQueryをベースに書かれたフロントエンドをReactで書き直すことを検討中です。
検討の一環として、ReactとjQueryは共存可能か調べたのでメモを残しておきます。

はじめに

Reactはチュートリアルを終えた段階で、まだ理解が浅いです。
その前提で以下お読みいただければ。

そもそも共存が必要なのか?

ReactはVirtualDOMという仕組みを通してDOM操作をするので、jQueryとの相性が悪そうだなというのはなんとなくわかります。

discuss.reactjs.org のjQuery with Reactにおいても

I don't mean to be rude but yes, don't use jQuery. In most cases you won't need anything from jQuery when properly using React.

という回答が寄せられています。

「必要でないなら使わない」というのは原則論としては賛成です。
が、現実としてjQuery plugin に頼りたくなるシチュエーションもあると思われます。

inherited a large application written in jQuery and from that standpoint it's quite logical to have both coexist for a while. Also, there may be libraries that do complex things which you don't want to rewrite in React yourself.

同様な意見もまた、同じトピックに寄せられています。

Reactの見解

Use React with Other Libraries に見解が書かれています。

You don't have to go full React. The component lifecycle events, especially componentDidMount and componentDidUpdate, are good places to put your other libraries' logic.

var App = React.createClass({
  ...

  componentDidMount: function() {
    $(this.refs.placeholder).append($('<span />'));
  },

  componentWillUnmount: function() {
    // Clean up work here.
  },

  ...
});

ReactDOM.render(<App />, mountNode);

必ずしも、全てをReactで書く必要はなく、上の例では jQuery で append しています。

サンプルも同様にjQueryを用いています。

VirtualDOM と Diff Algorithm

2013年と少し古いですが、Reactのdiff algorithm についてFacebook front-endチームの方が書いた記事がありました。
React’s diff algorithm

この仕組みを見る限り、Reactの管理下にあるDOMを破壊あるいは丸っと差し替えることはよろしくなさそうですが、例えば末端ノードに子要素を追加するのは安全そうに思えます。

まとめ

事前サーベイに基づく限りは、必要最低限の箇所に絞って容量用法を正しく守って使えばReactとjQueryは共存可能だと言えそうです。

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14