Search code examples
javascriptreactjswebreact-usememo

React useMemo not showing anything?


I have a react component where I use useMemo to save the posts of the forum website I am trying to build. The reason I try to memorize them is so that they wont rerender when I update the icons.

Here is the code:

    const postMapping = () => {props.listOfPosts.map((post, index) => {
        return (
        <div key={post.title} ind={index.toString()} className='postContainer'>
            <div className='postTitle'>{post.title}</div>
            <div className='postContent'>
                {post.content.slice(0, props.charLimit)}{post.content.length > props.charLimit ? 
                <span className='postMore curHover' onClick={e => showMore(e)}> DEVAMI...</span> : ""}
            </div>
            <div className='postIconContainer'>
                <img className='backgroundGrey commentImg curHover' src={icons.comment} alt="comments" />
                <div className='commentAmount amount'>{post.commentAmount}</div>
                <img className='backgroundGrey heartImg curHover' src={icons.heartEmpty} alt="heart" onClick={e => changeUpvoteIcon(e)}/>
                <div className='likeAmount amount'>{post.likeAmount}</div>
            </div>
        </div>);
    })}

    const listOfPosts = useMemo(() => postMapping, [props.listOfPosts]);

    return (
        <div id="postSectionContainer">
            {listOfPosts}
        </div>
    );
  };

  export default Post;

The problem is that my posts dont show up on the website, its just blank where there is suppose to be posts.


Solution

  • I was missing both calling the function like.

    const listOfPosts = useMemo(() => postMapping, [props.listOfPosts]); 
    

    insted I should have done this

    const listOfPosts = useMemo(() => postMapping(), [props.listOfPosts]); 
    

    also the return was missing in the postMapping function.

     const postMapping = () => {return props.listOfPosts.map((post, index) => {
    

    thanks to Felix Kling and Matt Carlotta for their help