skip to Main Content
  • Procedure:
const nextValue = counter + limit_counter; -> In here, nextValue = 2

console.log("haha", nextValue);

setCounter(nextValue); -> nextValue =2 for counter

console.log({ counter }); //but when I check, why is counter = 1 ??????

Could you explain me the reason why?? Thank you ^^

enter image description here

const nextValue = counter + limit_counter; -> In here, nextValue = 2

console.log("haha", nextValue);

setCounter(nextValue); -> nextValue =2 for counter

console.log({ counter }); //but when I check, why is counter = 1 ??????

I think in line 4, counter should equal to ‘2’ or I missed something?

2

Answers


  1. React’s setState function is async, which means you have to do something like this :

    useEffect(() => {
        console.log(counter);
    }, [counter ]);
    
    Login or Signup to reply.
  2. Use the callback version of the setCounter function.

    You will need an effect that listens for changes to counter.

    Note: In your provided code (screenshot), your CounterMain component is a controlled component. It manages its own state, so you do not need a counter in App. Also, increaseValue is unused.

    const { useEffect, useState } = React;
    
    const CounterMain = ({ increaseValue }) => {
      const [counter, setCounter] = useState(0);
      const limitCounter = 1;
    
      useEffect(() => {
        console.log("New value set to:", counter); // After update
      }, [counter]);
    
      const handleIncreaseValue = () => {
        setCounter((currValue) => {
          const nextValue = currValue + limitCounter;
          console.log("Setting new value", nextValue); // Stage it
          return nextValue;
        });
      };
    
      return (
        <button className="bg-cyan-400 p-2" onClick={handleIncreaseValue}>
          {counter}
        </button>
      );
    };
    
    const App = () => {
      return (
        <div className="App">
          <CounterMain />
        </div>
      );
    };
    
    ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    .as-console-wrapper { max-height: 5rem !important; }
    <script src="https://cdn.tailwindcss.com"></script>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

    Note: Your App and CounterMain components both have a counter state. If you need to hoist the state, move it to App.

    const { useEffect, useState } = React;
    
    const CounterMain = ({ increaseValue, value }) => {
      const limitCounter = 1;
    
      const handleIncreaseValue = () => {
        const nextValue = value + limitCounter;
        console.log("Setting new value", nextValue); // Stage it
        increaseValue(nextValue);
      };
    
      return (
        <button className="bg-cyan-400 p-2" onClick={handleIncreaseValue}>
          {value}
        </button>
      );
    };
    
    const App = () => {
      const [counter, setCounter] = useState(0);
      
      useEffect(() => {
        console.log("New value set to:", counter); // After update
      }, [counter]);
      
      return (
        <div className="App">
          <CounterMain value={counter} increaseValue={setCounter} />
          <div>Value: {counter}</div>
        </div>
      );
    };
    
    ReactDOM.createRoot(document.getElementById("root")).render(<App />);
    .as-console-wrapper { max-height: 5rem !important; }
    <script src="https://cdn.tailwindcss.com"></script>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

    If you want to share the state, you can use a context:

    const { createContext, useContext, useEffect, useReducer } = React;
    
    const CounterContext = createContext(null);
    const CounterDispatchContext = createContext(null);
    
    const CounterProvider = ({ children }) => {
      const [count, dispatch] = useReducer(countReducer, 0);
      return (
        <CounterContext.Provider value={count}>
          <CounterDispatchContext.Provider value={dispatch}>
            {children}
          </CounterDispatchContext.Provider>
        </CounterContext.Provider>
      );
    };
    
    const useCounter = () => useContext(CounterContext);
    const useCounterDispatch = () => useContext(CounterDispatchContext);
    
    const countReducer = (count, action) => {
      switch (action.type) {
        case 'increment': return count + action.amount;
        default: {
          throw Error('Unknown action: ' + action.type);
        }
      }
    };
    
    const CounterMain = () => {
      const count = useCounter();
      const dispatch = useCounterDispatch();
      const limitCounter = 1;
    
      const handleIncreaseValue = () => {
        const nextValue = count + limitCounter;
        console.log("Setting new value", nextValue); // Stage it
        dispatch({ type: 'increment', amount: limitCounter });
      };
    
      return (
        <button className="bg-cyan-400 p-2" onClick={handleIncreaseValue}>
          {count}
        </button>
      );
    };
    
    const App = () => {
      const count = useCounter();
      
      useEffect(() => {
        console.log("New value set to:", count); // After update
      }, [count]);
      
      return (
        <div className="App">
          <CounterMain />
          <div>Value: {count}</div>
        </div>
      );
    };
    
    ReactDOM.createRoot(document.getElementById("root")).render((
      <CounterProvider>
        <App />
      </CounterProvider>
    ));
    .as-console-wrapper { max-height: 5rem !important; }
    <script src="https://cdn.tailwindcss.com"></script>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search