Call a function from a functional component React Native

Viewed 202

I have the next problem, trying to call a function from a functional component, like shared in class components. My test code is:

import React, { useState } from 'react'

export const TestShared = () => {
    const [number, setNumber] = useState(0)

    const increase = () => {
        return setNumber(prevValue => prevValue + 1)
    }

    const getNumber = () => {
        return number
    }
}

In another file I import TestShared and trying to call the functions like TestShared.increase() or TestShared.getNumber() but of course is undefined.

How can I achieve this without using useContext? If there is any possible way.

Thank you!

2 Answers

You can check code here

const TestShared = () => {
 const [number, setNumber] = useState(0)

    const increase = () => {
        return setNumber(prevValue => prevValue + 1)
    }

    const getNumber = () => {
        return number
    }

    return {
        increase,
        getNumber
    };
}

export default TestShared ;

And where you want this function just import like this

import React, {useEffect} from "react";

import TestShared from './Helpers/TestShared' 

function MyComponent = () => {
    const {increase, getNumber} = TestShared();
}

I just wanted to expand a bit more on @arsian's answer after some experimentation.

  1. The names used when importing the objects in the parent component MUST match the exact same names of the exported elements in the child component, other way, the returning will be undefined:

Child component:

return {
        increase,
        getNumber
    };
export default TestShared ;

Parent component:

const {wrongName, getWrong} = TestShared(); //This will NOT work
console.log(wrongName); //undefined

const {increse, getNumber} = TestShared(); //This WILL work

  1. The returning elements can be the state and the setState function, actually, they can be of any type(function,array,object,list...). Also, the order of the elements when exporting or importing does not matter (the name does). For example,

Child component:

const arr = [0];
const obj = { a: 1 };
function fn() {
        console.log(arr, obj);
  };

return {
        number,
        setNumber,
        arr,
        obj,
        fn

    };

Parent component:

const {number, setNumber,obj,arr,fn} = TestShared();
console.log(arr,obj);
fn();

// [0],{a:1}

While the last point could be very intuitive, the first point gave me some troubles since I was thinking the order of the elements was the important factor and not the names. Because of that, I wanted to share my experimenting about sharing state between components in React.

Cheers.

Related