Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef() does not redraw the value

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>
  );
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading