What Happens in React When You Use CSS display none?
A component that goes from display: block -> display: none
- is not rendered
- shows up in the DOM tree
- shows up in the React DevTools Component tab
- the component is not destroyed
- the component stays alive
- the component keeps doing its work
- the cleanup function returned from useEffect is not executed
So what about a component whose initial value is display: none?
Just like when it goes from display: block -> none,
- it is not rendered
- it shows up in the DOM tree
- it shows up in the React DevTools Component tab
- the component does its work
- useEffect runs
Conclusion
- A React functional component returns a React element.
- It returns the React element regardless of whether the CSS display property is block or none
- All side effects are also executed at this stage
- The browser uses the returned React element to build the DOM tree and the CSSOM tree
- When building the rendering tree, elements with display: none are left out
- React plays no role at this stage
Example code
https://codesandbox.io/s/react-style-display-none-jf32k?file=/src/App.tsx
20210927
Leave a comment