1

I have two components which are located in different position in the hierarchy. One component has data which should be used in another component. I was trying to achieve this with custom hook. When I used in components I'm getting false, I want it to be true because I set it to true from component 1 so component 2 should get true. I don't know little bit confused on custom hooks.

Custom Hook

export const useShareData = () => {
  const [data, setData] = useState<boolean>(false)

  const setValue = (value: boolean) => {
    setData(value)
  }
  return [data, setValue]
}

Component 1

const [data, setData] = useShareData()
const dataToBeShared = true
useEffect(()=>{
   setData(dataToBeShared)
},[dataToBeShared])

Component 2

const [data] = useShareData()
console.log(data)

In component 2 the value is always false.

praveen guda
  • 97
  • 2
  • 10
  • Try using context – Learner Dec 07 '20 at 16:21
  • Cannot use context because there are many components between them don't want to use it, I'm trying to achieve with custom hook – praveen guda Dec 07 '20 at 16:24
  • I think there only three ways mostly used, lift the state, context and external package like redux , check this https://stackoverflow.com/questions/53451584/is-it-possible-to-share-states-between-components-using-the-usestate-hook-in-r or else you can use useGlobalState https://github.com/dai-shi/react-hooks-global-state, try it – Learner Dec 07 '20 at 16:27
  • `Cannot use context because there are many components between them don't want to use it` I don't understand. That's exactly what context is good for: skipping intermediate components that don't want to use it. – Nicholas Tower Dec 07 '20 at 16:29

1 Answers1

4

Creating a custom hook doesn't let data be shared, it just lets code be shared. While component 1 is rendering, if it calls const [data, setData] = useState<boolean>(false), it creates a state variable for component 1. This is the case whether it's written inline or extracted to a helper function (aka, a custom hook). Similarly, when component 2 calls useState, it creates state for component 2. The two states are not shared.

The standard approach for your issue is to lift state up to whatever component is the common ancestor of these two components, and then pass it down. If the common ancestor is nearby, props can be used; if it's far away, context becomes a more attractive option.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98