How to use reducer in react

Reducer example
Store Name you can give  as you wish as like any medical store, general store but here is I am using “Store” which will be export and use another pages. As below line:

export const Store = React.createContext(null)


import React, {useReducer} from 'react'
export const Store = React.createContext(null)

const showStDetails = {
    stList : [
        {stName: 'Sheo', stPhone: '9312875694'}

const updateStData = (state, action) => {
        case "add" :
            return {stList : state.stList.concat(action.payload)}

        default :
            return state

export default (props) => {
    const [studentdata, dispatchStData] = useReducer(updateStData, showStDetails)

        <Store.Provider value={{studentdata, dispatchStData}}>

Next, I have created a file “add student data” and its data will show on another page. My data is submitted via “useRef” hooks. As below code. When storing my data in the store then I use “useContext” hooks. Stored data will access to other pages.

import React,{useContext, useRef} from 'react'
import {Store} from '../mystore'

export default () => {
    const {dispatchStData} = useContext(Store)
    const stNameNew = useRef()
    const stPhoneNew = useRef()

    const addStudent = () => {
            dispatchStData ({type:'add', payload:{stName:stNameNew.current.value, stPhone:stPhoneNew.current.value}})

            <input type="text" placeholder="Student Name" ref={stNameNew} />
            <input type="tel" placeholder="Student Phone" ref={stPhoneNew} />
            <button onClick={addStudent}>Add Student</button>

Next step needs to access data as we have stored in the store, so I have created a new page where will show data “showStudent” as below example code:
import React, {useContext} from 'react'
import {Store} from '../mystore'

export default () => {

    const {studentdata} = useContext(Store)

    const renderStDetails = () => {
        return item => (
    return (

Now need to add all component in the App.js file as I have added in the below code:
import React from 'react';

import Store from './mystore'
import AddStudents from './components/addStudents'
import ShowStudents from './components/showStudent'

function App() {
  return (
    <div className="App">

export default App;

When you will start you server using with command “npm start” then you will found your result as below screenshot:

1 comment:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.