close

React – How to force a function component to render?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn React – How to force a function component to render? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

React – How to force a function component to render?

  1. React – How to force a function component to render?

    to force a function component to render
    const [rerender, setRerender] = useState(false); ... setRerender(!rerender); //whenever you want to re-render
    And this will ensure a re-render, since components re-render on state change

  2. React – How to force a function component to render?

    to force a function component to render
    const [rerender, setRerender] = useState(false); ... setRerender(!rerender); //whenever you want to re-render
    And this will ensure a re-render, since components re-render on state change

Method 1

This can be done without explicitly using hooks provided you add a prop to your component and a state to the stateless component’s parent component:

const ParentComponent = props => {
  const [updateNow, setUpdateNow] = useState(true)

  const updateFunc = () => {
    setUpdateNow(!updateNow)
  }

  const MyComponent = props => {
    return (<div> .... </div>)
  }

  const MyButtonComponent = props => {
    return (<div> <input type="button" onClick={props.updateFunc} />.... </div>)
  }

  return (
    <div> 
      <MyComponent updateMe={updateNow} />
      <MyButtonComponent updateFunc={updateFunc}/>
    </div>
  )
}

Method 2

You can simply do this

if you want to initiate a re-render, add a dummy state you can change to initiate a re-render.

const [rerender, setRerender] = useState(false);

...
setRerender(!rerender);     //whenever you want to re-render

And this will ensure a re-render, since components re-render on state change

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment