Home > Enterprise >  share hooks across components
share hooks across components

Time:05-06

I am trying to understand how to share hooks state across components. But it doesn't seem to be sharing. Am I doing something wrong here?

Home.js

export default function Home() {
    
    const [search, setSearch]= useState('');
    
    
    return (
        <div>
            <Input search={search} handleChange={setSearch}  />
            <Products search={search} handleChange={setSearch} />
        </div>
    )
}

Input.js

export default function Input({search, setSearch}) {
  
    

  const handleChange = (e) => {
      setSearch(e.target.value)
  }
  
    return (
    <div className='App'>

    <input 
    placeholder='search...' 
    value={search}
    onChange={handleChange}
    />


{search}
   

    </div>
  )
}

Live Example:

const { useState } = React;

/*export default*/ function Home() {
    
    const [search, setSearch]= useState('');
    
    
    return (
        <div>
            <Input search={search} handleChange={setSearch}  />
            <Products search={search} handleChange={setSearch} />
        </div>
    )
}

/*export default*/ function Input({search, setSearch}) {
  
    

  const handleChange = (e) => {
      setSearch(e.target.value)
  }
  
    return (
    <div className='App'>

    <input 
    placeholder='search...' 
    value={search}
    onChange={handleChange}
    />


{search}
   

    </div>
  )
}

const Products = ({search}) => {
    return <div>Product: {search}</div>;
};

ReactDOM.createRoot(document.getElementById("root"))
.render(<Home />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.development.js"></script>

CodePudding user response:

You pass handleSearch as prop in your Home component but Input is expecting setSearch, so just change this line in your Home

return (
  <div>
    <Input search={search} setSearch={setSearch}  />  // change here
    <Products search={search} handleChange={setSearch} />
  </div>
)
  • Related