Search code examples
reactjscomponentsreact-hooksrenderlifecycle

What is the right place to call a function before render in React?


I have some issue on understandsing the lifecycle in React, so iam using useEffects() since i do understand that it was the right way to call a method before the component rendered (the replacement for componentDidMount ).

  useEffect(() => {
    tagSplit = tagArr.split(',');
  });

And then i call tagSplit.map() function on the component, but it says that tagSplit.map is not a function

{tagSplit.map((item, index) => (
   <div className="styles" key={index}>
      {item}
   </div>
))}

Is there something wrong that i need to fix or was it normal ?


Solution

  • you can do something like this .

    function App() {
    
        const [arr, setArr] = useState([]);
    
        useEffect(() => {
            let tagSplit = tagArr.split(',');
            setArr(tagSplit);
        }, []);
    
        return (
            <>
                {arr.map((item, index) => (
                    <div className="styles" key={index}>
                        {item}
                    </div>
                ))}
            </>
        )
    }