Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React have something like Vue's keep-alive element?

Tags:

reactjs

vue.js

Vue keep-alive element will remember page state when back history page, hope React has something like that.

like image 945
Nate Gu Avatar asked Jan 08 '19 04:01

Nate Gu


People also ask

Can a React component render itself?

One of the cool things about React is that React components are essentially functions which return JSX. Therefore, just like with any other functions, React components can be recursive.

Is inheritance possible in React?

Inheritance allows the app to do the coupling between the parent-child component and reuse properties such as state values and function in its child components. React does not use inheritance except in the initial component class, which extends from the react package.

Is State a permanent storage in React?

Answer: B is the correct option. In ES6, there are three ways of defining your variables: var, let, and const. 14) What is a state in React? A permanent storage.


2 Answers

React does not have this type of feature, and a recent maintainer response on the same issue pretty strongly indicates they don't think this is a good idea. However, the same thread discusses a standard alternative, which is to implement your logic so that you are not deleting/creating the components but rather hiding and showing them. For instance, if you did something like this to support "tabs":

{this.state.activeTab === 1 &&
<MyFirstTabView/>
}
{this.state.activeTab === 2 &&
<MySecondTabView/>
}

then MyFirstTabView will obviously be destroyed when the second tab is selected. However, if you did it this way:

<MyFirstTabView className={this.state.activeTab === 1 ? 'active' : ''}/>
<MySecondTabView className={this.state.activeTab === 2 ? 'active' : ''}/>

and paired this with a CSS display: none or display: block rule, it would achieve a similar thing to Vue's keep-alive feature. It's not QUITE as efficient, but for common use-cases like tab switching, it's close.

like image 189
Chad Robinson Avatar answered Oct 20 '22 01:10

Chad Robinson


React offers keep alive through a package. To install this package, To install Run:

npm install --save react-keep-alive

import React from 'react';
import ReactDOM from 'react-dom';
import {
  Provider,
  KeepAlive,
} from 'react-keep-alive';
import Test from './views/Test';
 
ReactDOM.render(
  <Provider>
    <KeepAlive name="Test">
      <Test />
    </KeepAlive>
  </Provider>,
  document.getElementById('root'),
);
like image 23
Ali Tasawar Avatar answered Oct 20 '22 01:10

Ali Tasawar