Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom hook's state does not update across all components?

import { useState } from 'react';

export default function usePrivacyMode() {
  const [isPrivacyOn, setIsPrivacyOn] = useState(false);

  return {
    isPrivacyOn,
    setIsPrivacyOn
  };
}

This is my custom hook. I set the state in PrivacyIcons component, and then I use isPrivacyOn for show/hide values from a table based on the value. But in a different component the isPrivacyOn is not changed, it's changed only in PrivacyIcons? Why I can't change it in one component and then use the value across all components? Thanks.

like image 328
KRALQT Avatar asked Jan 23 '26 17:01

KRALQT


1 Answers

states are not meant to be shared across components. You are looking for useContext. This allows you to share a function and a state between components. React has an excellent tutorial on how to do it in the official documentation: https://reactjs.org/docs/hooks-reference.html#usecontext

For your specific example it would look something like this:

Your App.js

import { useState } from 'react';

export const PrivacyContext = createContext([]);

const App = (props) => {
   const [isPrivacyOn, setIsPrivacyOn] = useState(false); 
   return (
       <PrivacyContext.Provider value={[isPrivacyOn, setIsPrivacyOn]}>
           <ComponentUsingPrivacyContext />
           {props.children}
       </PrivacyContext.Provider>
   );
};

export default App;

Keep in mind that any component that wants access to that context must be a child of PrivacyContext

Any component that wants to use PrivacyContext:

import React, { useContext } from "react";
import {PrivacyContext} from "...your route";

const ComponentUsingPrivacyContext = (props) => {
    const  [isPrivacyOn, setIsPrivacyOn] = useContext(PageContext);
    return (
          <button onclick={setIsPrivacyOn}>
             Turn Privacy On
          </button>
          <span>Privacy is: {isPrivacyOn}</span>
     );
};
export default ComponentUsingPrivacyContext;
like image 136
Chayemor Avatar answered Jan 25 '26 08:01

Chayemor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!