Getting a state of from a component and show it as a value attribute inside a div?

Viewed 107

In functional components
I want to share a function I have with a few components, to prevent duplicated code. All I need is the state that the function changes.

Is it possible to get the state from UpdateNum.jsx component to other components (as I showed in the code) ?
Or, is it possible to pass this function to other components so I can use it multiple times ? ( also to send props to the function)

    import { useEffect, useState } from 'react';
    
    export default function UpdateNum(change) {
      const [numberCon , setNumber ] = useState(0);
    
      useEffect(() => {    
          setNumber(numberCon + 1)
      },[change])

      return numberCon;

    }

I want to get the numberCon state in Shop.jsx inside the value={} attribute

import UpdateNum from './functions/UpdateNum';

  <div className='cart-icon' value={''}>
            <FaShoppingCart size={40} />
          </div>

And also at Items.jsx as I do -

import UpdateNum from './functions/UpdateNum';

 return (
    <div >
      <h1 style={{ marginLeft: '30px' }}>
         <UpdateNum/> - Items  <br />
      </h1>
    </div>
  );
3 Answers

UpdateNum function should return a component , if you want that function to return the actual state value , then you need to make it as a custom hook.

  1. prefix the function name with use so that react knows that it's a custom hook.
import { useEffect, useState } from 'react';

export default function useNumberCon() {
  const [numberCon , setNumber ] = useState(0);

    function riseNum() {   //Some function to calculate a number
      setNumber(numberCon + 1)
  }

  return { numberCon, riseNum};
}
  1. Now in the component where you want to consume this numberCon and riseNum ( Shop.jsx and Items.jsx ) you can do this

// In Shop.jsx
const { numberCon, riseNum } = useNumberCon();

 ......
 ......

 <div className='cart-icon' value={numberCon}>
       <FaShoppingCart size={40} />
 </div>
  1. If your <Shop /> and the <Items /> are sibling to each other then you need to add the custom hook call ( step #2 ) in the parent component which wraps them .

Reference:

Custom Hooks

Lifting State Up

1)Isolate your required function and return in new file.

export const updateNum = (reciveParam) => {
   
        // do your calculation with reciveParam
        
        return value
     }

 

2)Import the function in required component

import updateNum from './util/updateNum';

const returnValue = updateNum(passParams);

3)Access here

<div className='cart-icon' value={returnValue}>
   <FaShoppingCart size={40} />
</div>
Related