Home > Net >  React Component not updating text when I change it
React Component not updating text when I change it

Time:12-14

When I click the increment button I expect the value displayed to go up but it stays the same

`

import * as React from 'react';

const MyComponent = () => {
  var count = 0;
  
  return (
    <div>
      <h1>Hello World</h1>
      <button onClick={() => count  }>{count}</button>
    </div>
  );
};

`

CodePudding user response:

You're not going to force a re render so your updated variable won't show.

import React, {useState} from 'react';

const MyComponent = () => {
const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Hello World</h1>
      <button onClick={() => setCount(count   1)}>{count}</button>
    </div>
  );
};

CodePudding user response:

In React you have to use state for rendering or updating.

This is example of increasing and decreasing counter with useState hook.

import React, { useState } from 'react';

export function App(props) {
const [count, setCount] = useState(0);

const handleIncrease = () => {
 setCount(count   1);
};

const handleDecrease = () => {
 setCount(count === 0 ? 0 : count - 1);
};

return (
 <div className='App'>
  <div>
    <h1>Hello World</h1>
    <button onClick={handleIncrease}>Increase</button>
    <button onClick={handleDecrease}>Decrease</button>
    <h3>Count is: {count}</h3>
  </div>
</div>
);
}

CodePudding user response:

I see here you are using Functional component, so have you tried using React hooks? useState() for example:

import * as React from 'react';

const MyComponent = () => {   
  const [count, setCount] = useState(0);
     return (
    <div>
      <h1>Hello World</h1>
      <button onClick={() => setCount(count   1)}>{count}</button>
    </div>   ); };

Try this maybe?

CodePudding user response:

You need to use useState hook so the component knows when to rerender and display new data.

I also recommend using useCallback hook to create memoized functions so you prevent unnecessary rerenders of your component (I know in this example it's an overkill but it's still good to know that).

You shouldn't, if possible, return arrow functions on your handlers like onClick - this will also cause the your component to not create new instances of your functions on each render, hence better performance (again not really relevant in this super simple case but a good thing to know nevertheless).

Here are some docs that you can read, these are a really good place to get started with React.

Here's also the code:

const MyComponent = () => {
  const [count, setCount] = useState(0);
  
  const handleCountIncrease = useCallback(() => {
    setCount((c) => c   1);
  }, [setCount]);
  
  return (
    <div>
      <h1>Hello World</h1>
      <button onClick={handleCountIncrease}>{count}</button>
    </div>
  )
}
  • Related