Managing store using hook

Gorakh Nath
1 min readSep 1, 2019

--

Now with the help of hook and advance concept of react we can manage the store of our application.

To manage the store first we can add a file and we will define a custom hook that will act same as the action and reducer work behind the scene of redux.

export const useStore = (shouldUpdate=true) => {

const setState = useState(mainState)[1];

const dispatch = (actionIdentifier, payload) => {

const newState = actions[actionIdentifier](mainState, payload);

mainState = { …mainState, …newState };

for (const listener of eventListeners) {

listener(mainState);

}

};

useEffect(() => {

if(shouldUpdate){

eventListeners.push(setState);

}

return () => {

if(shouldUpdate){

eventListeners = eventListeners.filter(li => li !== setState);

}

};

}, [setState,shouldUpdate]);

return [mainState, dispatch];

};

export const initStore = (userActions, initialState) => {

if (initialState) {

mainState = { …mainState, …initialState };

}

actions = { …actions, …userActions };

};

In above code we have defined mainState,action that we can update from our component.We can pass shouldUpdate as false from our component which is using React.memo to prevent the extra render of page for each item.

Wrapping up

We can manage the store without redux by using hook.For more detail how we can call the above configured store hook refer to the link I shared below:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Gorakh Nath
Gorakh Nath

No responses yet