Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why redux instead of session storage

Let's assume i have a small objects in my state of component "App". So to save the state in redux, why can't i save it in session storage? Is there any solid difference for this?

like image 339
Antriksh Sharma Avatar asked Jul 07 '19 15:07

Antriksh Sharma


2 Answers

Browser Storage allows only keys associated with string values, nothing complex, so the code required to simply get different types of data in and out of local/session is nasty, all by itself.

The "storing state" part of Redux is really the least interesting part. The important parts of Redux are the pattern of using actions and reducers, and that components can subscribe to those state changes, so that if a reducer updates the state, components using that will automatically re-render. Using browser storage techniques really only solve the "where does the state live" part. You'd still need mechanisms for updating that state and letting components know to re-render when the state updates

also session storage may be zero for eg simply using private browsing mode in Safari (including on iOS) will set the storage quota to zero

Also handling of localStorage and sessionStorage for a React application that treated it somewhat like state. It is the most error-prone, unpredictable, headache-inducing code in a codebase.

also you can use redux-locastorage to save store to local storage or redux-sessionstorage to save to session storage , if you still want to use them

like image 77
Reetesh Kumar Avatar answered Oct 04 '22 03:10

Reetesh Kumar


You can do so.

The difference is,

React is smart enough to update your DOM when you use state and update the state using setState. When you use setState in react app it simply re-renders your component and if you are using that state value in component to show some values / data that changes are updated on your component.

When you store data in sessionStorage then your app will not reacts automatically to change in sessionStorage values. In this case your component will not re-render and your changes are not updated on your component. But for this case you have a solution called forceUpdate()

from the docs,

Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.

Though you have forceUpdate, normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

like image 40
ravibagul91 Avatar answered Oct 04 '22 03:10

ravibagul91