0

I'm loading this library emoji-mart client side because it requires window object and then returning a component, while calling, the component is rendered twice to start with and then multiple times as parent component state changes.

function EmojiPicker(props = {}) {
  const ref = useRef()

  // loading the emojiMart lib clientside coz it requires 
  // window object
  useEffect(() => {
    import('emoji-mart').then((EmojiMart) => {
      new EmojiMart.Picker({ ...props, data, ref })
    })
  }, [])

  return <div ref={ref}></div>
}

function Feed = () => {
  
  const[value, setValue] = useState('')

  return (    
  ...
  ...
  <input value={value} onChange={handleChange}/>
  ...
  ...
  
  <EmojiPicker/>   
  /* EmojiPicker rendered twice and again and again whenever 
  input state changes */
    
  )
}

1 Answer 1

1

You can use React.memo to prevent unnecessary rerendering. It's easy to use, only you have to do is to wrap the component.

import React from 'react';

const EmojiPicker = React.memo(() => {
 ...
 return <div ref={ref}></div>
})
 

React.memo prevent rerender if there's no changes in props variables.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, Actually I'm looking at 2 emoji mart components on my screen to start with and they increase in number as the parent component rerenders(input state change here), I've tried dynamic import by next js, the error was 'Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object'
Did you try 'next/dynamic'?
yes, i just told you the error im getting with next/dynamic. I think it's rendered twice because of the react 18 strictmode but still there must a standard way to do it successfully

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.