Search code examples
reactjsreact-hooksreact-i18next

Is there a way to modify a value when its changed after rendering without useEffect


I have a react app that fetches the data that I need on render. When the data arrives, I have a useEffect in place that will format the data and update the variable required.

My issue now is that the format function that we are using has been changed to a hook, which I can't use in the useEffect anymore, and I was wondering if there was a way to basically replicate the process without the useEffect

For a simplified example, originally I had something similar to this component:

const MyComponent = ({myValue}) => {
    const [outputVal, setOutputVal] = useState(0);

    useEffect(() => {
        if (myValue != null) setOutputVal(formatCurrency(myValue));
    }, [myValue]);

[...]

formatCurrency was a simple function using the Intl.NumberFormat functionality, and would just convert the value as needed. I've now swapped to using the react-i18next library, which has other functionality that I want, but it uses hooks, which means I can't use the function within the useEffect.

I've tried to change it to use the function when the page loads, ie:

const [outputVal, setOutputVal] = useState(formatCurrency(myValue));

The issue that I've found though is that the initial value of myValue is null, and the function doesn't rerun when myValue is updated.

Any help or info on this would be great.


Solution

  • Since formatCurrency probably just formats the numerical value into a string, you could just run it on every render and treat it like any ordinary variable you'd use during rendering, i.e.:

    const MyComponent = ({myValue}) => {
        const outputVal = formatCurrency(myValue);
        return <p>{outputVal}</p>
    };