React context display

I am new in React and sitting about 4 day with the problem, that when i am using Context and inside Context is reducer, where I am trying to update value, I was checking through log the value and it’s updating as supposed but on the page display stays the default value all the time and not changing as expected. If someone could tell me where I am making mistake, I would appreciate it very much.

import CountextNum from "./countext-number";
import { useReducer } from "react";

const initialState = {
  number: 0,
};

const reducerFunc = (state, action) => {
  if(action.type === 'ADD') {
    
    state.number += action.val
    console.log(state.number)
    return state
  }
};

const NumberProvider = (props) => {
  const [mainState, dispatchState] = useReducer(reducerFunc, initialState);

  const addOne = () => {
    dispatchState({ type: "ADD", val: 1 });
  };

  const obj = {
    number: mainState.number,
    addOne: addOne,
  };

  return (
    <CountextNum.Provider value={obj}>{props.children}</CountextNum.Provider>
  );
};

export default NumberProvider;
=================================================
import React from 'react';
import NumberProvider from './store/NumberProvider';
import Header from './components/ui/Header';
import Add from './components/other/Add';


const App = () => {

  return (
   <NumberProvider>
    <Header />
    <Add />
   </NumberProvider>
  );
}

export default App;

==========================================

import React, { useContext } from 'react'
import CountextNum from '../../store/countext-number'



const Header = () => {
  const ctx = useContext(CountextNum)
  

  console.log(ctx)

  return (
    <header>
      <h3>{ctx.number}</h3>
    </header>
  )
}

export default Header

=======================================================

import React, { useContext } from 'react'
import CountextNum from '../../store/countext-number'

const Add = () => {

  const ctx = useContext(CountextNum)

  const addOneNumber = () => {
    ctx.addOne()
    console.log(ctx)
  }

  return (
    <button onClick={addOneNumber}>Add One</button>
  )
}

export default Add

In my code is Context and provider with reducer with all the logic. In one of my component is the button witch is updating the value and in another Header component is the value itself.

There is not styles so much or anything, I created the app only for try to understand where I make my mistake.

>Solution :

You are mutating the state, and since the state haven’t changed, the components are not re-rendered.

Create a new state object, with the updated property and use spread to include everything else from the current state:

const reducerFunc = (state, action) => {
  if(action.type === 'ADD') {
    return {
      ...state,
      number: state.number + action.val
    }
  }

  return state // return the current state for actions that aren't handled
};

Leave a Reply