Home > database >  useRef() does not redraw the value
useRef() does not redraw the value

Time:11-21

I have a useRef hook and two components. In one component, I increase the value on click by 1 unit, and in the second component, I draw the value. I pass the value itself through useContext.

Now the problem is that the value is not being redrawn. How can this be fixed?

export const ContactContext = React.createContext();

function App() {
  const countItem = useRef(1);

  const value = { countItem };

  return (
    <ContactContext.Provider value={value}>
        <div>
          <AddValue />
        </div>
        <div>
          <Logo />
        </div>
    </ContactContext.Provider>
  );
}

const AddValue = () => {
  const { countItem } = useContext(ContactContext);

  const addItemHandler = () => {
    countItem.current = countItem.current   1;
  };
  return (
    <>
      <div>
        <button
          onClick={addItemHandler}
        >
          <img src="plus.svg" alt="plus logo" />
        </button>
      </div>
    </>
  );
};

function Logo() {
  const { countItem } = useContext(ContactContext);

  return (
    <p data-testid="statistics">
      {`Count of channels: ${countItem.current}`} <br />
    </p>
  );
}

CodePudding user response:

useRef wont cause components in React to rerender

function App() {
  const [countItem, setCountItem] = useState(1)

  const value = { countItem, setCountItem };

In AddValue

const AddValue = () => {
  const { countItem, setCountItem } = useContext(ContactContext);

  const addItemHandler = () => {
   setCountItem(c => c  1)
  };

Reading the new React docs for state management will help Hope it helps

CodePudding user response:

Replace useRef with useState. useRef update the value but does not rerender.

  • Related