
Research
Malicious fezbox npm Package Steals Browser Passwords from Cookies via Innovative QR Code Steganographic Technique
A malicious package uses a QR code as steganography in an innovative technique.
redux-persist
Advanced tools
redux-persist is a library that allows you to save the Redux store in persistent storage, such as local storage, session storage, or even custom storage engines. This helps in maintaining the state of the application across page reloads.
Persisting Redux State
This feature allows you to persist the Redux state using a storage engine like local storage. The `persistReducer` function wraps your root reducer, and `persistStore` initializes the persistor.
const persistConfig = { key: 'root', storage }; const persistedReducer = persistReducer(persistConfig, rootReducer); const store = createStore(persistedReducer); const persistor = persistStore(store);
Rehydrating State
Rehydration is the process of loading the persisted state back into the Redux store when the application starts. This ensures that the state is restored to its previous state before the page was reloaded.
persistStore(store, null, () => { console.log('Rehydration complete'); });
Custom Storage Engines
You can use custom storage engines if the default local storage or session storage does not meet your requirements. This example shows how to create a noop storage engine for environments where local storage is not available.
import createWebStorage from 'redux-persist/lib/storage/createWebStorage'; const createNoopStorage = () => { return { getItem(_key) { return Promise.resolve(null); }, setItem(_key, value) { return Promise.resolve(value); }, removeItem(_key) { return Promise.resolve(); } }; }; const storage = typeof window !== 'undefined' ? createWebStorage('local') : createNoopStorage();
redux-localstorage is another library that allows you to persist Redux state to local storage. It is similar to redux-persist but offers a more modular approach, allowing you to choose different storage adapters and serializers.
redux-persist-transform-encrypt is a transformer for redux-persist that encrypts your persisted state. This is useful if you need to store sensitive information securely. It works as an add-on to redux-persist, providing encryption capabilities.
redux-persist-cookie-storage is a storage engine for redux-persist that uses cookies instead of local storage or session storage. This can be useful for server-side rendering or when you need to share state across different subdomains.
Persist and rehydrate a redux store.
Redux Persist is performant, easy to implement, and easy to extend.
Check out some recipes, or open an issue to discuss your use case.
Basic usage requires adding three lines to a traditional redux application:
import {persistStore, autoRehydrate} from 'redux-persist'
const store = autoRehydrate()(createStore)(reducer)
persistStore(store)
For per reducer rehydration logic, you can opt-in by adding a handler to your reducer:
import {REHYDRATE} from 'redux-persist/constants'
//...
case REHYDRATE:
if(action.key === 'myReducer'){
return {...state, ...action.payload, specialKey: processSpecial(action.payload.specialKey)}
}
return state
You may also need to configure the persistence layer, or take action after rehydration has completed:
persistStore(store, {blacklist: ['someTransientReducer']}, () => {
console.log('rehydration complete with state')
})
And if things get out of wack, just purge the storage
persistStore(store, config, callback).purge(['someReducer']) //or .purgeAll()
persistStore(store, [config, callback])
persistor object
.purge(keys)
.purgeAll()
.rehydrate(key, serialDataString)
autoRehydrate()
constants
import constants from 'redux-persist/constants'
. This includes rehydration action types, and other relevant constants.Redux-persist is very easy to extend with new functionality:
import reduxPersistImmutable from 'redux-persist-immutable'
import crosstabSync from 'redux-persist-crosstab'
const persistor = persistStore(store, {transforms: [reduxPersistImmutable]}, () => crosstabSync(persistor))
warning these api's may change without warning
import {getStoredState, autoRehydrate, persistStore} from 'redux-persist'
//... set up everything per normal: finalCreateStore, reducer etc.
const persistConfig = {
skipRestore: true
}
getStoredState(persistConfig, (err, initialState) => {
const store = finalCreateStore(reducer, initialState)
persistStore(store, persistConfig)
render(
<Root store={store} />,
document.getElementById('root')
</Root>
)
})
const persistor = persistStore(store)
const secondaryPersistor = persistStore(store, {storage: specialBackupStorage, skipRestore: false})
localStorage (default), react-native AsyncStorage, or a conforming custom storage api. Custom storage API should be an object with the following methods: setItem
getItem
removeItem
getAllKeys
each with the function signature as found in react-native AsyncStorage.
import {AsyncStorage} from 'react-native'
persistStore(store, {storage: AsyncStorage})
The core idea behind redux-persist is to provide performant persistence and rehydration methods. At the same time redux-persist is designed to minimize complexity by knowing as little about your application as possible.
Conceptually redux-persist encourages you to think on a per-reducer basis. This greatly simplifies the mental model (no filters or selectors!) and means that if you change your reducer schema, you will not need to mirror those changes in your persistence configuration.
Because persisting state is inherently stateful, persistStore
lives outside of the redux store. Importantly this keeps the store 'pure' and makes testing and extending the persistor much easier.
autoRehydrate is a store enhancer that automatically rehydrates state.
While auto rehydration works out of the box, individual reducers can opt in to handling their own rehydration, allowing for more complex operations like data transforms and cache invalidation. Simply define a handler for the rehydrate action in your reducer, and if the state is mutated, auto rehydrate will skip that key.
With autoRehydrate, actions dispatched before rehydration is complete are buffered and released immediately after rehydration is complete.
Auto rehydrate is provided as a convenience. In a large application, or one with atypical reducer composition, auto rehydration may not be convenient. In this case, simply omit autoRehydrate. Rehydration actions will still be fired by persistStore
, and can then be handled individually by reducers or using a custom rehydration handler.
JSON serialization and localStorage (which is sync!) can both hurt performance. To work around this redux-persist implements a few performance tricks:
config.debounce = 33
to stagger (debounce) the calls by 33ms intervals (i.e. 30fps).Additionally redux persist operates on a per reducer basis, which is a great lever for maximizing performance. If a piece of state is changing often (10+ times per second), isolate that state into it's own reducer, which will make the serialization and storage operations much faster.
FAQs
persist and rehydrate redux stores
We found that redux-persist demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
A malicious package uses a QR code as steganography in an innovative technique.
Research
/Security News
Socket identified 80 fake candidates targeting engineering roles, including suspected North Korean operators, exposing the new reality of hiring as a security function.
Application Security
/Research
/Security News
Socket detected multiple compromised CrowdStrike npm packages, continuing the "Shai-Hulud" supply chain attack that has now impacted nearly 500 packages.