Yesterday, I mistakenly created and deleted a post. Now, I am facing an issue with creating a component that requires specific styling. The problem arises when the componentDidMount() method causes flickering during the rendering process, as it takes some time for the CSS to be applied.
I suspect that my component is resource-intensive, leading to a slight lag or delay in the execution of componentDidMount()
. Therefore, I will only provide a snippet instead of a full demo, as the demo runs smoothly without any noticeable flickering.
To address this, I have tried integrating the value directly into the render method:
componentDidMount(){
// CSS rendering causing flickering :/
}
render(){
// Applying styles directly here returns the correct style instantly
if (Math.round(window.scrollY + window.innerHeight +50) >= Math.round(document.body.scrollHeight)) {
document.documentElement.style.setProperty('--background-transition', "")
document.documentElement.style.setProperty('--is-page-bottom', "orange");
document.documentElement.style.setProperty('--background-transition', "all 0.3s ease-out")
}
else{
//setIsPageBottom_CSSVariable("rgba(84, 80, 79,0.85)")
document.documentElement.style.setProperty('--background-transition', "")
document.documentElement.style.setProperty('--is-page-bottom', "purple");
document.documentElement.style.setProperty('--background-transition', "all 0.3s ease-out")
}
After discussing with someone, they suggested using React Hooks to handle this issue, as componentDidMount proved ineffective due to the flickering before applying the background color.
As I am new to React Hooks, can I directly set properties like document.documentElement.style.setProperty within useEffect()? Would this align well with the design principle of React Hooks?
While exploring solutions, I came across advice from the official React documentation which states that:
The render() function should be pure, meaning that it does not modify component state, it returns the same result each time itβs invoked, and it does not directly interact with the browser.
If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.
Considering this guidance, would it be acceptable to handle my styling within componentDidMount despite it not being the best practice? Some suggest using addeventlistener, but this approach seems more suitable for different scenarios than the one I am currently facing.
In conclusion, what alternative approach would you recommend to prevent flickering when setting CSS properties in componentDidMount()? How does this relate to leveraging React Hooks effectively?