简体   繁体   中英

Manually refresh or re-render component onClick in React

Is there a way in React to just refresh a component not the window but the component itself? This is so I can re-trigger a react-query. I know I can use useEffect() but what would be the way to do it?

So I know I could do, something like:

useEffect(() => {
     setFetchData(result);
}, [result]);

This would trigger the component to re-render when result changes. But how can you have a button that would manually refresh the component or re-render it.

You have to change a state to trigger component re-render. So, you can create any state and change it by clicking on a button:

const [value, setValue] = useState(false)

return (
...other jsx code
<button onClick={()=>setValue(!value)}>Trigger re-render</button>
)

If you are trying to refresh the component just to re-trigger a query from react-query , you'd better use refetch function provided by useQuery hook.

const { data, refetch, ... } = useQuery(...);

return (
  <>
    {(data?.yourQuery?.results || []).map(result => ...)}
    <button onClick={refetch}>Refetch!</button>
  </>
)

If there are some changes of data after calling refetch , the component will be automatically rerendered.

You can do it like this:

const [reload, setReload] = useState()
useEffect(() => {
     // Add your code here
}, [reload]);

return (
 <button onClick={() => setReload(!reload)} >Reload</button>
);

And anytime you click the button it will execute the code inside the useEffect and update the component.

You can do something like this

const [num, setNum] = useState(0)

return
(
<React.Fragment>
{num}
<button onClick={()=>setNum({prevNum => prevNum + 1)}>Click to Render</button>
</React.Fragment>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM